HttpClient快速上手

HttpClient是Apache下面的一个封装了HTTP协议的开源项目。虽然java.net包提供了基本的通过HTTP协议访问资源的功能,但是它不够灵活,功能性也不够。而HttpClient则恰好弥补了这一弊端。可以访问HttpClient官方首页了解更多。

要在项目中使用HttpClient有多种方式,例如直接从官方主页下载jar包,在下载页可以看到, 目前(2015-11-02)HttpClient最新版本是4.5.1。所以直接下载HttpClient的二进制包即可。同时最好也把HttpCore也下载下来,因为有可能会使用到。

如果项目是使用maven构建的,那么将下面的依赖加入到项目的pom文件中即可:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>

将jar包或者相关的依赖加入到项目中,就可以使用HttpClient了。

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(“http://localhost:8080/test");
StringEntity entity = new StringEntity(“{\”id\”:\”123456\”,\”name\”:\”sam\”}”);
entity.setContentType(“application/json”);
entity.setContentEncoding(“UTF-8”);
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
try{
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
System.out.println(“status:” + response.getStatusLine());
String output;
while((output = br.readLine()) != null) {
System.out.println(output);
}
}catch(Exception e){
e.printStackTrace();
}finally{
response.close();
httpClient.close();
}

以上代码是以post方式发送一个请求,其中参数是以json形式传送的。如果想以表单的形式传送参数的话,可以使用NameValuePair和UrlEncodedFormEntity这两个类,如下代码:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(“http://localhost:8080/test");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair(“id”, “123456”));
nvps.add(new BasicNameValuePair(“name”, “sam”));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, “utf-8”));
CloseableHttpResponse response = httpClient.execute(httpPost);
try{
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
System.out.println(“status:” + response.getStatusLine());
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
}catch(Exception e){
e.printStackTrace();
}finally{
response.close();
httpClient.close();
}

以上两段代码,便是使用HttpClient以Post方式发送一个请求。get请求这里就不作演示了。

注意到上两段代码中都有使用”utf-8”特别标明传送的参数是以UTF-8格式编码传送的。但,即便这样,在服务器端还是有可能会收到乱码。下面是另一个有可能避免乱码的方式,前提是上面的方式无效。

HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(“http://localhost:8080/test");
postMethod.getParams().setContentCharset(“utf-8”);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,”utf-8”);
postMethod.setRequestEntity(new StringRequestEntity(“{\”id\”:\”123456\”,\”name\”:\”sam\”}”, “application/json”, “utf-8”));
try{
int statusCode = client.executeMethod(postMethod);
System.out.println(“statusCode:” + statusCode);
System.out.println(postMethod.getResponseBodyAsString());
}catch(Exception e){
e.printStackTrace();
}finally{
postMethod.releaseConnection();
}

如果以上仍然有乱码,那么,就需要在服务端做一下编码转换即可。