使用HttpClient进行远程接口测试
前两天在工作中,项目组长给我了一个远程接口让我给测一下,因为是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();
}
}
}