一、对比
java发送Http post请求,一般在java中我们使用 httpcilent 包中的额 HttpPost 类;需要手动设置 setContentType 和 setContentEncoding;
代码书写看起来非常low 如下代码所示,而 spring 提供的 RestTemplate 提供的额方法则看起来就比较高大上一点:
public static String httpPostWithjson(String url, String json) throws IOException {
String result = "";
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
BasicResponseHandler handler = new BasicResponseHandler();
StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
result = httpClient.execute(httpPost, handler);
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}[b]
}
return result;
}
二、话不多说,直接给2个常用 RestTemplate 案例,复制即可使用:
1.提交JSON格式的数据
public class Testttttttt {
private static RestTemplate restTemplate = new RestTemplate();
public static String sendHttpRequestStatic(String url, JSONObject jsonParam) {
JSONObject result = new JSONObject();
try {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonParam.toJSONString(), httpHeaders);
ResponseEntity<String> response = restTemplate.postForEntity(url,request,String.class);
// Http 请求成功返回响应体
if (response.getStatusCodeValue() == 200) {
String resultStr = JSON.toJSONString(response.getBody()).replace("\\","");
return resultStr.substring(1,resultStr.length() - 1);
} else {
result.put("code","-1");
result.put("data","请求失败");
return result.toJSONString();
}
} catch (Exception e) {
e.printStackTrace();
result.put("code","-1");
result.put("data","请求异常");
return result.toJSONString();
}
}
}
2.提交表单数据(multipart/form-data)
public String sendHttpRequest(String url, JSONObject jsonParam, Map<String,String> param) {
JSONObject result = new JSONObject();
try {
String body;
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> mapParam = new LinkedMultiValueMap<>();
mapParam.setAll(param);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(mapParam, httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
// Http 请求成功返回响应体
if (response.getStatusCodeValue() == 200) {
String resultStr = JSON.toJSONString(response.getBody()).replace("\","");
return resultStr.substring(1,resultStr.length() - 1);
} else {
result.put("code","-1");
result.put("data","请求失败");
return result.toJSONString();
}
} catch (Exception e) {
e.printStackTrace();
result.put("code","-1");
result.put("data","请求异常");
return result.toJSONString();
}
}
三、看起来代码是不是高大上一点,当然RestTemplate还有许多其他调用方式,需要的朋友可以查看一下:其他方式 |