HttpClient工具类
maven依赖信息
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
代码具体实现和测试
package com.example.demo;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
public static void main(String[] args) throws IOException {
String url = "http://data.chi4rec.com.cn/xfr/toilet/addToiletData";
String json1 = "{\n" +
" \"loginName\":\"mhqapi\",\n" +
" \"loginPassword\":\"123456\"\n" +
"}";
String json="{\n" +
"\t\"temperature\": \"23.00\",\n" +
"\t\"humidity\": \"89\",\n" +
"\t\"carbonDioxide\": \"888.20\",\n" +
"\t\"hydrogenSulfide\": \"0\",\n" +
"\t\"ammonia\": \"0\",\n" +
"\t\"water\": 8,\n" +
"\t\"electric\": 8,\n" +
"\t\"paper\": 16,\n" +
"\t\"soap\": 16,\n" +
"\t\"peopleFlow\": 90,\n" +
"\t\"groupType\": 0\n" +
"}";
String facilityId ="115337";
String token = "dc794bce-3f14-4735-af85-eb36d4afcde8";
String postJson = doPostJson(url, json,facilityId,token);
JSONObject jsonObject = JSONObject.parseObject(postJson);
System.out.println(jsonObject);
Map<String,String> map = new HashMap<>();
String urlSend ="";
String host = "http://wuliu.market.alicloudapi.com";
String path = "/kdi";
String appCode="233d5f704a8643ba9676b52";
String orderNo = "611179134601924";
String company ="";
map.put("no",orderNo);
if(!("".equals(company)) || company!=null){
map.put("company",company);
}
if(!("".equals(company)) && company!=null){
urlSend = host + path + "?no=" + orderNo +"&type="+company;
}else{
urlSend = host + path + "?no=" + orderNo;
}
String postMsg = HttpClientUtils.doGetToWuliu(urlSend,appCode);
}
public static String doGetUrlContansParam(String url) {
JSONObject jsonObject = null;
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
jsonObject = JSONObject.parseObject(content);
result = jsonObject.get("nonce").toString();
}
} finally {
response.close();
}
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doGet(String url, Map<String, String> param) {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url, Map<String, String> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
httpPost.setEntity(entity);
}
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostString(String url, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostJson(String url, String json,String headerparam,String token) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("headerparam",headerparam);
httpPost.setHeader("token",token);
Header[] tokens = httpPost.getHeaders("token");
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGetToWuliu(String urlSend ,String appCode) throws IOException {
try {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
URL url = new URL(urlSend);
HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
httpURLCon.setRequestProperty("Authorization", "APPCODE " + appCode);
int httpCode = httpURLCon.getResponseCode();
if (httpCode == 200) {
br= new BufferedReader(new InputStreamReader(httpURLCon.getInputStream()));
String line = null;
while((line =br.readLine())!=null){
line =new String(line.getBytes());
sb.append(line);
}
System.out.println("正常请求计费(其他均不计费)");
System.out.println("获取返回的json:");
br.close();
return sb.toString();
} else {
Map<String, List<String>> map = httpURLCon.getHeaderFields();
String error = map.get("X-Ca-Error-Message").get(0);
if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
System.out.println("AppCode错误 ");
return "AppCode错误";
} else if (httpCode == 400 && error.equals("Invalid Url")) {
System.out.println("请求的 Method、Path 或者环境错误");
return "请求的 Method、Path 或者环境错误";
} else if (httpCode == 400 && error.equals("Invalid Param Location")) {
System.out.println("参数错误");
return "参数错误";
} else if (httpCode == 403 && error.equals("Unauthorized")) {
System.out.println("服务未被授权(或URL和Path不正确)");
return "\"服务未被授权(或URL和Path不正确)";
} else if (httpCode == 403 && error.equals("Quota Exhausted")) {
System.out.println("套餐包次数用完 ");
return "套餐包次数用完";
} else {
System.out.println("参数名错误 或 其他错误");
System.out.println(error);
return "参数名错误 或 其他错误"+error;
}
}
} catch (MalformedURLException e) {
System.out.println("URL格式错误");
return "URL格式错误";
} catch (UnknownHostException e) {
System.out.println("URL地址错误");
return "URL地址错误";
} catch (Exception e) {
}
return null;
}
private static String read(InputStream is) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
line = new String(line.getBytes(), "utf-8");
sb.append(line);
}
br.close();
return sb.toString();
}
}