HttpClient一个http_post请求例子

Posted Jourly的测试博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient一个http_post请求例子相关的知识,希望对你有一定的参考价值。

package httpclient.httpclient;

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
	public void testPost() {
		//1.创建客户端访问服务器的httpclient对象
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		//2.定义请求的url
		String url = "https://XXX.XXX.com/NC1000001";
		//3.以请求的连接地址创建get/post请求对象
		HttpPost post = new HttpPost(url);
		//如果有header请求,添加header请求
		post.addHeader("x-api-key", "XXX");
		post.addHeader("x-lang", "en-US");
		try {
			//4.向服务器发送请求,并获取返回数据
			CloseableHttpResponse response = httpClient.execute(post);
			//获取返回的所有headers
			Header[] headers = response.getAllHeaders();
			for (Header header : headers) {
				System.out.println(header);
			}
			//获取返回的状态
			int status = response.getStatusLine().getStatusCode();
			System.out.println(status);
			//获取HttpEntity消息载体对象
			HttpEntity entity = response.getEntity();
			// EntityUtils中的toString()方法转换服务器的响应数据
			String str = EntityUtils.toString(entity, "utf-8");
			System.out.println("服务器的响应是:" + str);
			//5.关闭连接
			httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		HttpClientUtil util = new HttpClientUtil();
		util.testPost();
	}
}

运行结果:

Date: Wed, 06 Sep 2017 09:49:39 GMT
Server: Apache/2.4.7 (Ubuntu)
Cache-Control: no-cache, private
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Content-Length: 150
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json
200
服务器的响应是:{"id":1000001,"tracking_id":"NC1000001"}

以上是关于HttpClient一个http_post请求例子的主要内容,如果未能解决你的问题,请参考以下文章

使用Apache HttpClient实现多线程下载的小例子

httpClient Post例子,Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete

如何在 Android 中使用 HTTPClient 以 JSON 格式发送 POST 请求?

Http协议以及Httpclient

如何在 HttpClient 的请求中添加、设置和获取 Header?

通过httpClient请求文件流(普通文件和压缩文件)示例