restTemplate 的用法

 
JSONObject json = new JSONObject();
json.put("mid", mid);
json.put("tid", tid);
 
 //调用普通接口
HttpURLConnection httpURLConnection = null;
BufferedReader ino = null;
PrintWriter out = null;
try {
URL url = new URL(APIurl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content_Type","application/json");
httpURLConnection.setRequestProperty("Accept_Charset","UTF-8");
httpURLConnection.setRequestProperty("contentType","UTF-8");
//发送POST请求参数
out = new PrintWriter(httpURLConnection.getOutputStream());
// out = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");
out.write(strReqJsonStr);
// out.println(strReqJsonStr);
out.flush();
//读取响应
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
StringBuffer content = new StringBuffer();
String tempStr = null;
ino = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
while ((tempStr=ino.readLine()) != null){
content.append(tempStr);
}
System.out.println("content:"+content.toString());
//转换成json对象
JSONObject respJson = JSON.parseObject(content.toString());
String resultCode = respJson.getString("errCode");
if("SUCCESS".equals(resultCode)){
//成功继续走下面逻辑
}else{

//失败
}

}
return null;

} catch (RestClientException e) {
logger.error("调用银商接口出现异常", e.toString() );
return null;
}

RestTemplate 方法实现
private final RestTemplate restTemplate;

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json;charset=UTF-8");
HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(paramsMap), httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(APIurl, POST, httpEntity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
JSONObject result = JSON.parseObject(response.getBody());
if (result.getInteger("code") == 200) {

}

}

猜你喜欢

转载自www.cnblogs.com/xiaoxiaojuan/p/9717861.html