1 importcom.alibaba.fastjson.JSONObject;2 importorg.apache.http.HttpEntity;3 importorg.apache.http.NameValuePair;4 importorg.apache.http.client.entity.UrlEncodedFormEntity;5 importorg.apache.http.client.methods.CloseableHttpResponse;6 importorg.apache.http.client.methods.HttpGet;7 importorg.apache.http.client.methods.HttpPost;8 importorg.apache.http.client.utils.URIBuilder;9 importorg.apache.http.entity.StringEntity;10 importorg.apache.http.impl.client.CloseableHttpClient;11 importorg.apache.http.impl.client.HttpClients;12 importorg.apache.http.message.BasicHeader;13 importorg.apache.http.message.BasicNameValuePair;14 importorg.apache.http.util.EntityUtils;15 importorg.slf4j.Logger;16 importorg.slf4j.LoggerFactory;17 importjava.util.ArrayList;18 importjava.util.List;19
20 /**
21 * HttpClient发送POST请求22 */
23 public classHttpClientService {24
25
26 /**
27 * 发送POST请求28 *@paramurl29 *@parammap集合30 *@returnJSON31 *@throwsException32 */
33 public static Object sendPost(String url, Map map) throwsException{34 JSONObject jsonObject = null;35 CloseableHttpClient client = null;36 CloseableHttpResponse response = null;37 try{38 /**
39 * 创建一个httpclient对象40 */
41 client =HttpClients.createDefault();42 /**
43 * 创建一个post对象44 */
45 HttpPost post = newHttpPost(url);46
47 JSONObject jsonParam = newJSONObject();48 Set set =map.keySet();49 for (String str : set) {//将Map转换成JSONObject
50 jsonParam.put(str, map.get(str));51 }52 JSONArray jsonArray = newJSONArray();53 jsonArray.add(jsonParam);//将JSONObject转换成JSONArray入参
54
55 /**
56 * 设置上传byte[]数组文件流57 builder.addBinaryBody("data", byteOutStream.toByteArray(), ContentType.MULTIPART_FORM_DATA, "AudioFile.wav");58 HttpEntity entity = builder.build();59 */
60
61 /**
62 * 设置上传单一对象63 */
64 StringEntity entity = new StringEntity(jsonArray.toString(), "utf-8");65
66 /**
67 * 设置请求的内容68 */
69 post.setEntity(entity);70 /**
71 * 设置请求的报文头部的编码72 */
73 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));74 /**
75 * 设置请求的报文头部的编码76 */
77 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));78 /**
79 * 执行post请求80 */
81 response =client.execute(post);82 /**
83 * 获取响应码84 */
85 int statusCode =response.getStatusLine().getStatusCode();86 if (200 ==statusCode){87 /**
88 * 通过EntityUitls获取返回内容89 */
90 String result = EntityUtils.toString(response.getEntity(),"UTF-8");91 /**
92 * 转换成json,根据合法性返回json或者字符串93 */
94 try{95 jsonObject =JSONObject.parseObject(result);96 returnjsonObject;97 }catch(Exception e){98 returnresult;99 }100 }else{101 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");102 }103 }catch(Exception e){104 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);105 }finally{106 response.close();107 client.close();108 }109 return null;110 }111
112 }