Apache HttpClient 示例 - CloseableHttpClient

可以使用ApacheHttpClient将HTTP请求从客户端代码发送到服务器。在上一个教程中,我们了解了如何使用HttpURLConnection 从Java程序本身执行GET和POST HTTP请求操作。今天我们将以相同的示例项目为例,但使用** Apache HttpClient** 来执行GET和POST请求操作。

Apache HttpClient

ApacheHttpClient,HttpClient Example,HttpClient Java,ApacheHttpClient Example,closeablehttpclient为了了解GET和POST请求的详细信息,我强烈建议您也看看早期的example ]。** ApacheHttpClient** 非常广泛地用于从Java程序本身发送HTTP请求。如果您使用的是Maven,那么您可以添加以下依赖项,它将包括使用Apache HttpClient所需的所有其他依赖项。

1<dependency>
2    <groupId>org.apache.httpcomponents</groupId>
3    <artifactId>httpclient</artifactId>
4    <version>4.4</version>
5</dependency>

但是,如果您没有使用Maven,则需要在项目构建路径中添加以下jar文件才能使其工作。

1.HTTPCLIENT-4.4.jar 2.HTTPcore-4.4.jar 3.Commons-Logging-1.2.jar 4.Commons-codec-1.9.jar

如果您使用的是其他版本的ApacheHttpClient,而不是Maven,那么只需创建一个临时Maven项目来获取兼容JAR的列表,如下图所示。ApacheHttpClient,HttpClient example现在只需将JAR复制到您的项目库目录中,它将使您避免任何兼容性问题,并将节省查找JAR和从互联网下载的时间。现在我们有了所有必需的依赖项,下面是使用ApacheHttpClient发送GET和POST请求的步骤。

1.使用helper类HttpClients创建CloseableHttpClient的实例。 2.根据HTTP请求类型创建HttpGetHttpPost实例。 3.使用_addHeader_method添加必需的头部,如User-Agent、Accept-Ending等。 4.POST创建NameValuePair列表,添加所有表单参数。然后将其设置为HttpPost实体。 5.通过执行HttpGet或HttpPost请求获取CloseableHttpResponse。 6.从响应中获取需要的状态码、错误信息、响应html等详细信息。 7.最后关闭ApacheHttpClient资源。

下面是我们拥有的最后一个程序,展示了如何在Java程序本身中使用Apache HttpClient 执行HTTP GET和POST请求。

 1package com.journaldev.utils;
 2
 3import java.io.BufferedReader;
 4import java.io.IOException;
 5import java.io.InputStreamReader;
 6import java.util.ArrayList;
 7import java.util.List;
 8
 9import org.apache.http.HttpEntity;
10import org.apache.http.NameValuePair;
11import org.apache.http.client.entity.UrlEncodedFormEntity;
12import org.apache.http.client.methods.CloseableHttpResponse;
13import org.apache.http.client.methods.HttpGet;
14import org.apache.http.client.methods.HttpPost;
15import org.apache.http.impl.client.CloseableHttpClient;
16import org.apache.http.impl.client.HttpClients;
17import org.apache.http.message.BasicNameValuePair;
18
19public class ApacheHttpClientExample {
20
21    private static final String USER_AGENT = "Mozilla/5.0";
22
23    private static final String GET_URL = "https://localhost:9090/SpringMVCExample";
24
25    private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";
26
27    public static void main(String[] args) throws IOException {
28    	sendGET();
29    	System.out.println("GET DONE");
30    	sendPOST();
31    	System.out.println("POST DONE");
32    }
33
34    private static void sendGET() throws IOException {
35    	CloseableHttpClient httpClient = HttpClients.createDefault();
36    	HttpGet httpGet = new HttpGet(GET_URL);
37    	httpGet.addHeader("User-Agent", USER_AGENT);
38    	CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
39
40    	System.out.println("GET Response Status:: "
41    			+ httpResponse.getStatusLine().getStatusCode());
42
43    	BufferedReader reader = new BufferedReader(new InputStreamReader(
44    			httpResponse.getEntity().getContent()));
45
46    	String inputLine;
47    	StringBuffer response = new StringBuffer();
48
49    	while ((inputLine = reader.readLine()) != null) {
50    		response.append(inputLine);
51    	}
52    	reader.close();
53
54    	// print result
55    	System.out.println(response.toString());
56    	httpClient.close();
57    }
58
59    private static void sendPOST() throws IOException {
60
61    	CloseableHttpClient httpClient = HttpClients.createDefault();
62    	HttpPost httpPost = new HttpPost(POST_URL);
63    	httpPost.addHeader("User-Agent", USER_AGENT);
64
65    	List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
66    	urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));
67
68    	HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
69    	httpPost.setEntity(postParams);
70
71    	CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
72
73    	System.out.println("POST Response Status:: "
74    			+ httpResponse.getStatusLine().getStatusCode());
75
76    	BufferedReader reader = new BufferedReader(new InputStreamReader(
77    			httpResponse.getEntity().getContent()));
78
79    	String inputLine;
80    	StringBuffer response = new StringBuffer();
81
82    	while ((inputLine = reader.readLine()) != null) {
83    		response.append(inputLine);
84    	}
85    	reader.close();
86
87    	// print result
88    	System.out.println(response.toString());
89    	httpClient.close();
90
91    }
92
93}

当我们运行上面的程序时,我们得到与浏览器中接收到的类似的输出html。

1GET Response Status:: 200
2<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 7, 2015 1:01:22 AM IST. </P></body></html>
3GET DONE
4POST Response Status:: 200
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html>
6POST DONE

以上就是ApacheHttpClient示例,它包含了许多您可以使用的实用程序方法。所以我建议你去看看,以便更好地了解。

Published At
Categories with 技术
Tagged with
comments powered by Disqus