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"}