================================================
测试所用包版本:
================================================
一、工具类
package com.bjsasc.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
/**
* 发送GET请求
*
* @param urlStr
* 请求地址
* @return 返回响应数据字符串(响应失败,返回null)
*/
public static String sendGet(String urlStr) {
if (urlStr == null) {
return null;
}
// 1.创建get请求
HttpGet httpGet = new HttpGet(urlStr);
// 2.发送请求
String resposeBody = null;// 存储响应数据
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpGet);
// 3.处理响应
int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.释放资源
closeAll(response, httpClient, httpGet);
}
return resposeBody;
}
/**
* 发送POST请求(application/json)【推荐使用】
*
* @param urlStr
* 请求地址
* @param jsonParamStr
* 请求参数json串
* @return 返回响应数据字符串(响应失败,返回null)
*/
public static String sendPost(String urlStr, String jsonParamStr) {
if (urlStr == null || jsonParamStr == null) {
return null;
}
// 1.创建post请求
HttpPost httpPost = new HttpPost(urlStr);
// 2.装配post请求参数
httpPost.setHeader("Content-type", "application/json;charset=utf-8");
httpPost.setHeader("Connection", "Close");//HTTP Connection的 close设置允许客户端或服务器中任何一方关闭底层的连接双方都会要求在处理请求后关闭它们的TCP连接
StringEntity entity = new StringEntity(jsonParamStr.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
String resposeBody = null;// 存储响应数据
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
// 3.发送请求
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
// 4.处理响应
int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
if (statusCode == 200) {// 响应成功
HttpEntity httpEntity = response.getEntity(); 获取响应实体
resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.释放资源
closeAll(response, httpClient, httpPost);
}
return resposeBody;
}
/**
* 发送POST请求
*
* @param urlStr
* 请求地址
* @param paramMap
* 请求参数
* @return 返回响应数据字符串(响应失败,返回null)
*/
public static String sendPost2(String urlStr, Map<String, String> paramMap) {
if (urlStr == null) {
return null;
}
if (paramMap == null) {
return null;
}
// 1.创建post请求
HttpPost httpPost = new HttpPost(urlStr);
// 2.装配post请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
String resposeBody = null;// 存储响应数据
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
httpPost.setEntity(urlEncodedFormEntity);
httpPost.setHeader("Content-type", "application/json;charset=utf-8");
// 3.发送请求
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPost);
// 4.处理响应
int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
if (statusCode == 200) {// 响应成功
HttpEntity httpEntity = response.getEntity(); 获取响应实体
resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.释放资源
closeAll(response, httpClient, httpPost);
}
return resposeBody;
}
/**
* 发送Delete请求
*
* @param urlStr
* 请求地址
* @return 返回响应数据字符串(响应失败,返回null)
*/
public static String sendDelete(String urlStr) {
if (urlStr == null) {
return null;
}
// 1.创建delete请求
HttpDelete httpDelete = new HttpDelete(urlStr);
// 2.发送请求
String resposeBody = null;// 存储响应数据
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpDelete);
// 3.处理响应
int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.释放资源
closeAll(response, httpClient, httpDelete);
}
return resposeBody;
}
/**
* 发送PUT请求
*
* @param urlStr
* 请求地址
* @return 返回响应数据字符串(响应失败,返回null)
*/
public static String sendPut(String urlStr) {
if (urlStr == null) {
return null;
}
// 1.创建put请求
HttpPut httpPut = new HttpPut(urlStr);
// 2.发送请求
String resposeBody = null;// 存储响应数据
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
response = httpClient.execute(httpPut);
// 3.处理响应
int statusCode = response.getStatusLine().getStatusCode();// 响应状态码
if (statusCode == 200) {
HttpEntity httpEntity = response.getEntity();
resposeBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4.释放资源
closeAll(response, httpClient, httpPut);
}
return resposeBody;
}
/**
* 释放资源
*
* @param response
* @param httpClient
* @param httpRequest
*/
private static void closeAll(CloseableHttpResponse response, CloseableHttpClient httpClient,
HttpRequestBase httpRequest) {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
if (httpRequest != null) {
httpRequest.releaseConnection();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、测试类
package com.bjsasc.test;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjsasc.util.HttpClientUtils;
public class TestMain {
public static void main(String[] args) {
/*
* 1.测试get请求
*/
String urlStr1 = "http://localhost:8082/ssm/test/getData_get?rootNodeFlag=0¤tPageNum=1&perPageNum=10";
String resposeBody1 = HttpClientUtils.sendGet(urlStr1);
if(resposeBody1 != null) {
System.out.println("【响应内容1】:" + resposeBody1);
//json字符串转json对象
JSONObject jsonObj = JSON.parseObject(resposeBody1);
//获取json属性
int code1 = jsonObj.getIntValue("code");
System.out.println("【响应内容中的code1】:"+code1);
} else {//请求失败,响应为null
System.out.println("resposeBody1:"+resposeBody1);
}
/*
* 2.1.测试post请求【推荐使用】
*/
String urlStr = "http://localhost:8889/workflow-form/horizon/workflow/rest/user/login.wf";
String jsonParamStr="{\"loginName\":\"lisi\",\"password\":\"1234\",\"tenantCode\":\"\"}";
String resposeBody = HttpClientUtils.sendPost(urlStr, jsonParamStr);
JSONObject jsonObj = null;
if(resposeBody != null) {
System.out.println("【响应内容】:" + resposeBody);
jsonObj = JSON.parseObject(resposeBody);
if(jsonObj.getIntValue("code") == 0 && jsonObj.getBooleanValue("success") == true) {
JSONObject userObj = jsonObj.getJSONObject("data");
String horizonToken = userObj.getString("accessToken");
System.out.println(horizonToken);
horizonToken = EscapeUnescape.escape(horizonToken).replaceAll("/\\+/g", "%2B");
System.out.print(horizonToken);
} else {
//TODO
}
} else {//请求失败,响应为null
System.out.println("resposeBody:"+resposeBody);
}
/*
* 2.测试post2请求
*/
String urlStr2 = "http://localhost:8082/ssm/test/getData_post";
Map<String, String> map = new HashMap<String, String>();
map.put("rootNodeFlag", "0");// 参数1
map.put("currentPageNum", "1");// 参数2
map.put("perPageNum", "10");// 参数3
String resposeBody2 = HttpClientUtils.sendPost2(urlStr2, map);
if(resposeBody2 != null) {
System.out.println("【响应内容2】:" + resposeBody2);
//json字符串转json对象
JSONObject jsonObj = JSON.parseObject(resposeBody2);
//获取json属性
int code2 = jsonObj.getIntValue("code");
System.out.println("【响应内容中的code2】:"+code2);
} else {//请求失败,响应为null
System.out.println("resposeBody2:"+resposeBody2);
}
/*
* 3.测试delete请求
*/
String urlStr3 = "http://localhost:8082/ssm/test/getData_delete?rootNodeFlag=0¤tPageNum=1&perPageNum=10";
String resposeBody3 = HttpClientUtils.sendDelete(urlStr3);
if(resposeBody2 != null) {
System.out.println("【响应内容3】:" + resposeBody3);
//json字符串转json对象
JSONObject jsonObj = JSON.parseObject(resposeBody3);
//获取json属性
int code3 = jsonObj.getIntValue("code");
System.out.println("【响应内容中的code3】:"+code3);
} else {//请求失败,响应为null
System.out.println("resposeBody3"+resposeBody3);
}
/*
* 4.测试put请求
*/
String urlStr4 = "http://localhost:8082/ssm/test/getData_put?rootNodeFlag=0¤tPageNum=1&perPageNum=10";
String resposeBody4 = HttpClientUtils.sendPut(urlStr4);
if(resposeBody4 != null) {
System.out.println("【响应内容4】:" + resposeBody4);
//json字符串转json对象
JSONObject jsonObj = JSON.parseObject(resposeBody4);
//获取json属性
int code4 = jsonObj.getIntValue("code");
System.out.println("【响应内容中的code4】:"+code4);
} else {//请求失败,响应为null
System.out.println("resposeBody4"+resposeBody4);
}
}
}