使用HttpClient请求方式JSON和JSON(FROM)
请求方式 : JSON(FROM)
public Map httpResponseFrom(String url, Map<String, String> params){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = null;
HttpGet httpGet = null;
BufferedReader reader = null;
CloseableHttpResponse httpResponse = null;
String result = "";
Map<String, String> resultMap = null;
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
for (String key : params.keySet()) {
builder.addPart(key,new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity reqEntity = builder.build();
httpPost = new HttpPost(url);
httpPost.setEntity(reqEntity);
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(90000).setSocketTimeout(90000).setSocketTimeout(30000).build());
httpResponse = httpClient.execute(httpPost);
}
reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
result += inputLine;
}
if (!StringUtils.isBlank(result)) {
return resultMap = (Map) JSON.parse(result);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(httpResponse != null)
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
请求方式 : JSON
public Map httpResponse(String url, String body){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = null;
HttpGet httpGet = null;
BufferedReader reader = null;
CloseableHttpResponse httpResponse = null;
String result = "";
Map<String, String> resultMap = null;
try {
StringEntity urlEntity = new StringEntity(new String(body.getBytes(), "ISO-8859-1"));
httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(urlEntity);
httpPost.setConfig(RequestConfig.custom().setConnectTimeout(90000).setSocketTimeout(90000).build());
httpResponse = httpClient.execute(httpPost);
reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
result += inputLine;
}
if (!StringUtils.isBlank(result)) {
return resultMap = (Map) JSON.parse(result);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if(httpResponse != null)
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}