利用java实现发送http或get请求的方法有哪些-创新互联
这篇文章将为大家详细讲解有关利用java实现发送http或get请求的方法有哪些,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

一、第一种方式,通过HttpClient方式,代码如下:
public static String httpGet(String url, String charset)
throws HttpException, IOException {
String json = null;
HttpGet httpGet = new HttpGet();
// 设置参数
try {
httpGet.setURI(new URI(url));
} catch (URISyntaxException e) {
throw new HttpException("请求url格式错误。"+e.getMessage());
}
// 发送请求
HttpResponse httpResponse = client.execute(httpGet);
// 获取返回的数据
HttpEntity entity = httpResponse.getEntity();
byte[] body = EntityUtils.toByteArray(entity);
StatusLine sL = httpResponse.getStatusLine();
int statusCode = sL.getStatusCode();
if (statusCode == 200) {
json = new String(body, charset);
entity.consumeContent();
} else {
throw new HttpException("statusCode="+statusCode);
}
return json;
} 网站栏目:利用java实现发送http或get请求的方法有哪些-创新互联
网站地址:http://www.scyingshan.cn/article/poedp.html


咨询
建站咨询
