原本使用 org.apache.commons.httpclient 方法封装进行 http 接口测试,由于支持异步请求和 H2 不易,因此研究采用 OkHttpClient 方式进行替换
为了保证兼容性,采用的方法调用尽量与原来的 org.apache.commons.httpclient 使用方法保持一致
OkHttpClient 的强大大家大可百度瞅瞅
1.响应结果 response.body().string 一直不能正常显示,后来改用原有封装的读 byte 流转 String 方式解决
/**
* 构造函数初始化
*/
private OkHttpClientMethod(){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(30, TimeUnit.SECONDS);//读取超时
builder.connectTimeout(10,TimeUnit.SECONDS);//连接超时
builder.writeTimeout(60,TimeUnit.SECONDS);//写入超时
//协议
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP_1_1);
protocols.add(Protocol.HTTP_2);
builder.protocols(protocols);
//ssl
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
builder.hostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
builder.sslSocketFactory(sslParams.sSLSocketFactory,sslParams.trustManager);
//cookie 自动存储
builder.cookieJar(new CookieJar() {
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
cookieStore.put(url.host(),cookies);
}
public List<Cookie> loadForRequest(HttpUrl url) {
List<Cookie> cookies = cookieStore.get(url.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
});
mOkHttpClient = builder.build();
}
/**
* 单例实现
* @return
*/
public static OkHttpClientMethod getInstance(){
if(mInstance == null){
synchronized (OkHttpClientMethod.class){
if(mInstance == null){
mInstance = new OkHttpClientMethod();
}
}
}
return mInstance;
}
/**
* 设置Header头
* @param headersParams
* @return
*/
private Headers setHeaders(Map<String,Object> headersParams){
Headers headers = null;
Headers.Builder headerBuilder = new Headers.Builder();
if(headersParams != null){
for (String key:headersParams.keySet()){
headerBuilder.add(key,headersParams.get(key).toString());
}
}
headers = headerBuilder.build();
return headers;
}
/**
* 设置get连接拼接参数
* @param params
* @return
*/
private String setUrlParams(Map<String,Object> params){
StringBuffer param = new StringBuffer();
int i = 0;
if(params == null){
return param.toString();
}
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
try {
param.append(key).append("=").append(URLEncoder.encode(params.get(key).toString(),"UTF-8")); //字符串拼接
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
return param.toString();
}
/**
* 设置post表单请求
* @param params
* @return
*/
private RequestBody setPostBody(Map<String,Object> params){
RequestBody body = null;
FormBody.Builder formBodyBuilder = new FormBody.Builder();
if(params != null){
for (String key:params.keySet()){
formBodyBuilder.add(key,params.get(key).toString());
}
}
body = formBodyBuilder.build();
return body;
}
/**
* Get请求
* @param url
* @param urlParams
* @param headerParams
* @return
*/
public Object getMethod(String url,Map<String, Object> urlParams, Map<String, Object> headerParams){
Request request = new Request.Builder()
.url(url + setUrlParams(urlParams))
.headers(setHeaders(headerParams))
.get()
.build();
Call call = mOkHttpClient.newCall(request);
JSONObject jsonResult = new JSONObject();
log.info("Http info:" + request.toString());
log.info("Http Header:" + request.headers().toString());
try {
Response response = call.execute();
String result = InputStreamUtils.inputStreamTOString(response.body().byteStream(),"UTF-8");
log.info("Http Result:" + result);
if (response.isSuccessful()){
jsonResult = JSONObject.fromObject(result);
return jsonResult;
}
} catch (Exception e) {
e.printStackTrace();
}
return jsonResult;
}
/**
* 异步Get请求
* @param url
* @param urlParams
* @param headerParams
* @return
*/
public void getAsyncMethod(String url,Map<String, Object> urlParams, Map<String, Object> headerParams,OkHttpClientCallBack okHttpRequestCallBack){
Request request = new Request.Builder()
.url(url + setUrlParams(urlParams))
.headers(setHeaders(headerParams))
.get()
.build();
Call call = mOkHttpClient.newCall(request);
log.info("Http info:" + request.toString());
log.info("Http Header:" + request.headers().toString());
try {
call.enqueue(okHttpRequestCallBack);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 异步Get请求 原生
* @param url
* @param urlParams
* @param headerParams
* @return
*/
public void getAsyncNativeMethod(String url,Map<String, Object> urlParams, Map<String, Object> headerParams,Callback callback){
Request request = new Request.Builder()
.url(url + setUrlParams(urlParams))
.headers(setHeaders(headerParams))
.get()
.build();
Call call = mOkHttpClient.newCall(request);
log.info("Http info:" + request.toString());
log.info("Http Header:" + request.headers().toString());
try {
call.enqueue(callback);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 异步Post请求
* @param url
* @param urlParams
* @param bodyParams
* @param headerParams
* @return
*/
public void postAsyncMethod(String url, Map<String, Object> urlParams, Map<String, Object> bodyParams, Map<String, Object> headerParams,OkHttpClientCallBack okHttpRequestCallBack){
Request request = new Request.Builder()
.url(url + setUrlParams(urlParams))
.headers(setHeaders(headerParams))
.post(setPostBody(bodyParams))
.build();
Call call = mOkHttpClient.newCall(request);
log.info("Http info:" + request.toString());
log.info("Http Header:" + request.headers().toString());
log.info("Http params:" + request.body().toString());
try {
call.enqueue(okHttpRequestCallBack);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送JSON 异步post请求
* @param url
* @param urlParams
* @param jsonParams
* @param headerParams
* @return
*/
public void postJsonAsyncMethod(String url,Map<String,Object> urlParams,Object jsonParams,Map<String,Object> headerParams,OkHttpClientCallBack okHttpRequestCallBack){
RequestBody requestBody = FormBody.create(MediaType.parse("application/json"),JSONObject.fromObject(jsonParams).toString());
Request request = new Request.Builder()
.url(url + setUrlParams(urlParams))
.headers(setHeaders(headerParams))
.post(requestBody)
.build();
Call call = mOkHttpClient.newCall(request);
log.info("Http info:" + request.toString());
log.info("Http Header:" + request.headers().toString());
log.info("Http params:" + request.body().toString());
try {
call.enqueue(okHttpRequestCallBack);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试 JSON 异步JSON请求
*/
@Test
public void testPostAsnycJsonHttp() throws Exception{
//设置url
String url = "http://192.168.3.14:8980/xxxxxxxxx";
Map<String,Object> headers = new HashMap<String,Object>();
headers.put("Content-Type","application/json");
headers.put("Connection","Upgrade, HTTP2-Settings");
headers.put("Upgrade","h2c");
JSONObject params = new JSONObject();
params.put("searchAll",0);
OkHttpClientCallBack okHttpClientCallBack = new OkHttpClientCallBack();
OkHttpClientMethod okHttpClientMethod = OkHttpClientMethod.getInstance();
okHttpClientMethod.postJsonAsyncMethod(url,null,params,headers,okHttpClientCallBack);
for (int i = 0; i < 10; i++) {
System.out.println("我是主线程,线程Id为:" + Thread.currentThread().getId());
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Long beforeTime = System.currentTimeMillis();
System.out.println("你说啥就是啥:" + beforeTime);
System.out.println(okHttpClientCallBack.getResult());
Long afterTime = System.currentTimeMillis();
System.out.println("该干啥就干啥:" + Long.toString(afterTime - beforeTime));
}