使用Apache的HttpClient发送GET和POST请求的步骤如下:
1. 使用帮助类HttpClients创建CloseableHttpClient对象.
2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
7. 最后关闭HttpClient资源.
public static String getContentByBody(String url, String body) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(body);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(res.getEntity());// 返回json格式:
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
1. 使用帮助类HttpClients创建CloseableHttpClient对象.
2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
7. 最后关闭HttpClient资源.
public static String getContentByBody(String url, String body) {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
JSONObject response = null;
try {
StringEntity s = new StringEntity(body);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(res.getEntity());// 返回json格式:
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}