Apache HttpClient 示例 – CloseableHttpClient

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

Apache HttpClient 可以被简述为“Apache HTTP 客户端”。

为了理解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包使其正常工作。

    1. httpclient-4.4.jar

 

    1. httpcore-4.4.jar

 

    1. commons-logging-1.2.jar

 

    1. commons-codec-1.9.jar

http客户端-4.4.jar
http核心-4.4.jar
常见日志-1.2.jar
常见编解码-1.9.jar

如果您使用的是其他版本的Apache HttpClient并且不使用Maven,那么只需创建一个临时的Maven项目来获取兼容的jar列表,如下图所示。然后将这些jar文件复制到您的项目lib目录中,这样可以避免任何兼容性问题,并且节省从互联网下载jar文件的时间。现在,我们已经获得了所有所需的依赖项,下面是使用Apache HttpClient发送GET和POST请求的步骤。

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

 

    1. 根据HTTP请求类型创建HttpGet或HttpPost的实例。

 

    1. 使用addHeader方法添加必需的头部,如User-Agent、Accept-Encoding等。

 

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

 

    1. 通过执行HttpGet或HttpPost请求获取CloseableHttpResponse。

 

    1. 从响应中获取所需的详细信息,如状态代码、错误信息、响应HTML等。

 

    最后关闭Apache HttpClient资源。

以下是我们展示如何在Java程序中使用Apache HttpClient执行HTTP GET和POST请求的最终程序。

package com.Olivia.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, 2015 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

以上就是Apache HttpClient示例的全部内容,它包含了许多实用方法供您使用。因此,我建议您去查看它们以便更好地理解。

发表回复 0

Your email address will not be published. Required fields are marked *


广告
将在 10 秒后关闭
bannerAds