博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Apache HttpClient示例– CloseableHttpClient
阅读量:2532 次
发布时间:2019-05-11

本文共 6369 字,大约阅读时间需要 21 分钟。

Apache HttpClient can be used to send HTTP requests from client code to server. In our last tutorial, we saw how to use to perform GET and POST HTTP request operations from java program itself. Today we will take the same example project but use Apache HttpClient to perform GET and POST request operations.

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

Apache HttpClient (Apache HttpClient)

For the sake of understanding the GET and POST request details, I would strongly suggest you to have a look at the too. Apache HttpClient is very widely used for sending HTTP requests from java program itself. If you are using Maven, then you can add below dependencies and it will include all other required dependencies for using Apache HttpClient.

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

org.apache.httpcomponents
httpclient
4.4

However if you are not using Maven, then need to add following jars in your project build path for it to work.

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

  1. httpclient-4.4.jar

    httpclient-4.4.jar
  2. httpcore-4.4.jar

    httpcore-4.4.jar
  3. commons-logging-1.2.jar

    commons-logging-1.2.jar
  4. commons-codec-1.9.jar

    commons-codec-1.9.jar

If you are using some other version of Apache HttpClient and not using Maven, then just create a temporary Maven project to get the list of compatible jars, as shown in image below.

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

Now just copy the jars to your project lib directory, it will save you from any compatibility issues as well as it will save time in finding jars and downloading from internet.

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

Now that we have all the required dependencies, below are the steps for using Apache HttpClient to send GET and POST requests.

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

  1. Create instance of CloseableHttpClient using helper class HttpClients.

    使用帮助程序类HttpClients创建CloseableHttpClient实例。
  2. Create HttpGet or HttpPost instance based on the HTTP request type.

    根据HTTP请求类型创建HttpGetHttpPost实例。
  3. Use addHeader method to add required headers such as User-Agent, Accept-Encoding etc.

    使用addHeader方法添加所需的标头,例如User-Agent,Accept-Encoding等。
  4. For POST, create list of NameValuePair and add all the form parameters. Then set it to the HttpPost entity.

    对于POST,创建NameValuePair列表并添加所有表单参数。 然后将其设置为HttpPost实体。
  5. Get CloseableHttpResponse by executing the HttpGet or HttpPost request.

    通过执行HttpGet或HttpPost请求来获取CloseableHttpResponse
  6. Get required details such as status code, error information, response html etc from the response.

    从响应中获取所需的详细信息,例如状态代码,错误信息,响应html等。
  7. Finally close the apache HttpClient resource.

    最后关闭apache HttpClient资源。

Below is the final program we have showing how to use Apache HttpClient for performing HTTP GET and POST requests in a java program itself.

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

package com.journaldev.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
urlParameters = new ArrayList
(); 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(); }}

When we run above program, we get similar output html as received in the browser.

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

GET Response Status:: 200	Home

Hello world!

The time on the server is March 7, 2015 1:01:22 AM IST.

GET DONEPOST Response Status:: 200
User Home Page

Hi Pankaj Kumar

POST DONE

That’s all for Apache HttpClient example, it contains a lot of utility methods that you can use. So I would suggest you to check them out for better understanding.

这就是Apache HttpClient示例的全部内容,其中包含许多可以使用的实用程序方法。 因此,我建议您检查一下以便更好地理解。

翻译自:

转载地址:http://bumzd.baihongyu.com/

你可能感兴趣的文章
C_数据结构_链表
查看>>
kettle-连接控件
查看>>
Coursera--Neural Networks and Deep Learning Week 2
查看>>
C#中的委托和事件(续)【来自张子扬】
查看>>
机器学习部分国内牛人
查看>>
模拟Sping MVC
查看>>
Luogu 3261 [JLOI2015]城池攻占
查看>>
java修饰符
查看>>
C# Using 用法
查看>>
javascript函数的几种写法集合
查看>>
BZOJ第1页养成计划
查看>>
漫漫修行路
查看>>
js与jQuery的区别——每日一记录
查看>>
MyBatis 处理sql中的 大于,小于,大于等于,小于等于
查看>>
Lunix文件的读写权限问题
查看>>
Liferay 7:portlet name
查看>>
PostgreSQL9.6.3的REDIS测试
查看>>
解决pycharm问题:module 'pip' has no attribute 'main'
查看>>
002 lambda表达式
查看>>
springboot添加自定义注解
查看>>