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) {

}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM