Apache的HttpClient可以被用于从客户端发送HTTP请求到服务器端,下面给出一个用HttpClient执行GET和POST请求的操作方法
添加maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
请求步骤
- 使用帮助类HttpClients创建CloseableHttpClient对象.
- 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
- 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
- 可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
- 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
- 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
- 释放连接。无论执行方法是否成功,都必须释放连接
示例如下
public static String httpPost(String host, int port, byte[] buf)
{
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
String url = "http://" + host + ":" + port;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();//设置请求和传输超时时间
httpPost.setConfig(requestConfig);
httpPost.addHeader("User-Agent", "Mozilla/5.0");
ByteArrayEntity entity = new ByteArrayEntity(buf);
httpPost.setEntity(entity);
httpResponse = httpClient.execute(httpPost);
reader = new BufferedReader(new InputStreamReader(
httpResponse.getEntity().getContent()));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
}catch (Exception var){
var.printStackTrace();
}finally {
if(reader != null){
reader.close();
}
if(httpResponse != null){
httpResponse.close();
}
httpClient.close();
}
return response.toString();
}
public void httpGet() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com/");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}