Apache HttpClient示例– CloseableHttpClient

时间:2020-02-23 14:29:39  来源:igfitidea点击:

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

Apache HttpClient

为了理解GET和POST请求的详细信息,我强烈建议您也看一下前面的示例。
Apache HttpClient被广泛用于从Java程序本身发送HTTP请求。
如果使用的是Maven,则可以添加以下依赖项,它将包括使用Apache HttpClient所需的所有其他依赖项。

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.4</version>
</dependency>

但是,如果您不使用Maven,则需要在项目构建路径中添加以下jar,使其起作用。

  • httpclient-4.4.jar
  • httpcore-4.4.jar
  • commons-logging-1.2.jar
  • commons-codec-1.9.jar

如果您正在使用其他版本的Apache HttpClient而不是使用Maven,则只需创建一个临时Maven项目即可获取兼容jar的列表,如下图所示。

现在,只需将jars复制到您的项目lib目录中,它将使您免受任何兼容性问题的困扰,还可以节省查找jars和从Internet下载的时间。

现在我们有了所有必需的依赖关系,下面是使用Apache HttpClient发送GET和POST请求的步骤。

  • 使用辅助类HttpClients创建CloseableHttpClient的实例。

  • 根据HTTP请求类型创建HttpGet或者HttpPost实例。

  • 使用addHeader方法添加所需的标头,例如User-Agent,Accept-Encoding等。

  • 对于POST,创建NameValuePair列表并添加所有表单参数。
    然后将其设置为HttpPost实体。

  • 通过执行HttpGet或者HttpPost请求获取CloseableHttpResponse

  • 从响应中获取所需的详细信息,例如状态代码,错误信息,响应html等。

  • 最后关闭ApacheHttpClient资源。

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

package com.theitroad.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ApacheHttpClientExample {

	private static final String USER_AGENT = "Mozilla/5.0";

	private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

	private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

	public static void main(String[] args) throws IOException {
		sendGET();
		System.out.println("GET DONE");
		sendPOST();
		System.out.println("POST DONE");
	}

	private static void sendGET() throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(GET_URL);
		httpGet.addHeader("User-Agent", USER_AGENT);
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

		System.out.println("GET Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		//print result
		System.out.println(response.toString());
		httpClient.close();
	}

	private static void sendPOST() throws IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(POST_URL);
		httpPost.addHeader("User-Agent", USER_AGENT);

		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

		HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
		httpPost.setEntity(postParams);

		CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

		System.out.println("POST Response Status:: "
				+ httpResponse.getStatusLine().getStatusCode());

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		//print result
		System.out.println(response.toString());
		httpClient.close();

	}

}

当我们运行上述程序时,我们将获得与浏览器中相似的输出html。

GET Response Status:: 200
<html><head>	<title>Home</title></head><body><h1>	Hello world!  </h1><P>  The time on the server is March 7, 2014 1:01:22 AM IST. </P></body></html>
GET DONE
POST Response Status:: 200
<!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>
POST DONE