1.环境
- JDK1.8
- httpclient 4.5.2
2.Maven依赖
<dependencies>
<!--httpclient依赖-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--JSON转换工具-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--以JDK1.8编译-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
3.HttpCli工具类
package cn.memoing.httpcli;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
public class HttpCliUtils {
private static final CloseableHttpClient client = HttpClients.createDefault();
public static void doPost(String url, JSONObject json, Header... headers) {
HttpPost httpPost = new HttpPost(url);
if (headers != null && headers.length > 0) {
httpPost.setHeaders(headers);
}
StringEntity entity = null;
try {
entity = new StringEntity(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
executeHttpRequest(httpPost);
}
public static void doPut(String url, JSONObject json, Header... headers) {
HttpPut httpPut = new HttpPut(url);
if (httpPut != null && headers.length > 0) {
httpPut.setHeaders(headers);
}
StringEntity entity = null;
try {
entity = new StringEntity(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPut.setEntity(entity);
executeHttpRequest(httpPut);
}
public static void doGet(String url, Map<String, Object> paramsMap, Header... headers) {
String parpms = "";
if (paramsMap != null && !(paramsMap.isEmpty())) {
String paramMapFormat = paramsMap.entrySet().stream()
.filter(a->!"".equals(a.getValue()))
.map(a -> {
String temp = "";
if (a.getValue() instanceof int[]) {
if (((int[]) a.getValue()).length > 1) {
int[] values = (int[]) a.getValue();
for (int i = 0; i < values.length - 1; i++) {
temp += a.getKey() + "=" + values[i] + "&";
}
temp += a.getKey() + "=" + values[values.length - 1];
}
} else {
if (!"".equals(a.getValue())) {
temp = a.getKey() + "="+a.getValue();
}
}
return temp;
}).collect(Collectors.joining("&"));
String param = Arrays.stream(paramMapFormat.split("&+")).collect(Collectors.joining("&"));
System.out.println("paramMapFormat = " + paramMapFormat);
if (!("".equals(param))) {
if(param.substring(0,1).equals("&")){
param = param.substring(1);
}
parpms = "?" + param;
}
}
String absUrl = url + parpms;
System.out.println("absUrl = " + absUrl);
HttpGet httpGet = new HttpGet(absUrl);
if (headers != null && headers.length > 0) {
httpGet.setHeaders(headers);
}
executeHttpRequest(httpGet);
}
public static void doDelete(String url, Map<String, Object> paramsMap, Object[] objParms, Header... headers) {
String parpms = "";
if (paramsMap != null && !(paramsMap.isEmpty())) {
parpms = paramsMap.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
parpms = "?" + parpms;
} else if (objParms != null && objParms.length > 0) {
parpms = "/";
for (int i = 0; i < objParms.length - 1; i++) {
parpms += objParms[i] + "/";
}
parpms += objParms[objParms.length - 1];
}
String absUrl = url + parpms;
System.out.println("absUrl = " + absUrl);
HttpDelete httpDelete = new HttpDelete(url + parpms);
if (headers != null && headers.length > 0) {
httpDelete.setHeaders(headers);
}
executeHttpRequest(httpDelete);
}
private static void executeHttpRequest(HttpRequestBase httpRequestBase) {
CloseableHttpResponse httpResponse = null;
try {
httpResponse = client.execute(httpRequestBase);
HttpEntity httpEntity = httpResponse.getEntity();
formatPrint(EntityUtils.toString(httpEntity));
} catch (IOException e) {
e.printStackTrace();
}
}
private static void formatPrint(String jsonObj) {
int level = 0;
StringBuffer jsonForMatStr = new StringBuffer();
for (int index = 0; index < jsonObj.length(); index++) {
char c = jsonObj.charAt(index);
if (level > 0 && '\n' == jsonForMatStr.charAt(jsonForMatStr.length() - 1)) {
jsonForMatStr.append(getLevelStr(level));
}
switch (c) {
case '{':
case '[':
jsonForMatStr.append(c + "\n");
level++;
break;
case ',':
jsonForMatStr.append(c + "\n");
break;
case '}':
case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
System.out.println(jsonForMatStr);
}
private static String getLevelStr(int level) {
StringBuffer levelStr = new StringBuffer();
for (int levelI = 0; levelI < level; levelI++) {
levelStr.append(" ");
}
return levelStr.toString();
}
}