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