前兩天在工作中,項目組長給我了一個遠程接口讓我給測一下,因為是http協議,所以我首先想到了用httpClient工具類來測試,網上一查,找到了好多示例代碼,隨便復制了一個demo進行了簡單的修改,結果怎麼測試都是連接超時,試了很多個demo也不好使,最後發現是因為我們公司訪問外網是通過代理,所以在進行測試的時候需要配置代理。
以下是我的測試程序
用到的jar包:
package com.lym.test;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import com.google.gson.JsonObject;
public class HttpClientTest {
public static void main(String args[]) throws Exception {
// 創建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
// 依次是目標請求地址,端口號,協議類型
HttpHost target = new HttpHost("61.144.244.6:8888/sztmerchant/merchant/addIsztMerchant.htm", 8888, "http");
// 依次是代理地址,代理端口號,協議類型
HttpHost proxy = new HttpHost("proxy3.bj.petrochina", 8080, "http");
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
// 請求地址
HttpPost httpPost = new HttpPost("http://61.144.244.6:8888/sztmerchant/merchant/addIsztMerchant.htm");
// 設置頭信息
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setConfig(config);
// 創建參數json串
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("merchantNo", "33300911238");
jsonObj.addProperty("merchantName", "電商運營生產測試1238");
String jsonStr = jsonObj.toString();
System.out.println("parameters: " + jsonStr);
StringEntity entity;
try {
entity = new StringEntity(jsonStr, "UTF-8");
httpPost.setEntity(entity);
CloseableHttpResponse response = closeableHttpClient.execute(target, httpPost);
// getEntity()
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印響應內容
System.out.println("result: " + EntityUtils.toString(httpEntity, "UTF-8"));
}else {
System.out.println("無響應內容");
}
// 釋放資源
if(closeableHttpClient != null) {
closeableHttpClient.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
HttpClient4 用法 由HttpClient3 升級到 HttpClient4 必看 http://www.linuxidc.com/Linux/2015-06/119100.htm
HttpClient 教程 http://www.linuxidc.com/Linux/2015-06/119099.htm
使用HttpClient實現文件的上傳下載 http://www.linuxidc.com/Linux/2014-07/104303.htm
Android 實現 HttpClient 請求Https http://www.linuxidc.com/Linux/2014-05/102306.htm
Android使用HttpClient下載圖片 http://www.linuxidc.com/Linux/2014-05/101855.htm
HttpClient使用詳解 http://www.linuxidc.com/Linux/2014-08/104945.htm