不介紹太多,只介紹實用的,像getObject, getEntity我都不介紹,只介紹一個exchange()函數就夠了,最後會附上我們公司的代碼。
下面對RestTemplate的函數做詳細說明及使用技巧:
無論GET請求,還是POST請求,exchange參數位置是一樣的。
public <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables)
參數介紹:
1、url: 該參數是請求的url, 有時請求參數在Param或着在Path裏面,這時最好的處理方式是使用佔位符處理。注:不要直接把參數值直接寫上去,直接寫上參數值會請求失敗。正確寫的法如:
http://localhost:8085/userservice/v1/users/query?queryParam={queryParam}
2、method:是調用的方法,如POST, GET。
3、requestEntity:請求的類名,會放入Body中。
4、responseType:返回的類名,返回後,會自動的轉換爲該類。
5、uriVariables:指的是參數。很多文章都說默認爲PATH,其實不是,他是填充佔位符用的。在URL中,哪裏有佔位符,就會填充哪裏。如下所示:
(1)Param位置填充。
http://localhost:8085/userservice/v1/users/query?queryParam={queryParam}, map爲:
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("queryParam", "{\"startPage\":1,\"pageSize\":50}");
自動填充佔位{queryParam}.
(2)在Path位置
http://localhost:8085/userservice/v1/users/query/{userId}, 那就會自動填充userId
我的代碼如下:
package com.system.http.util; import com.system.http.entity.ErrorCode; import com.system.http.entity.RetEntity; import org.springframework.http.*; import org.springframework.web.client.RestTemplate; import java.util.Map; import java.util.Map.Entry; /** * Http協議的發送類,用於服務之間的調用。 */ public class HttpSendUtils { public static final int MAP_EMPTY_FLAG = 0; public static final int MAP_NOT_EMPTY_FLAG = 1; /** * Http協議的GET請求。 *@param url 請求的URL,包含IP,端口號,還有請求的URI。 *@param sessionId, 服務之間調用的會話id。 *@param authId ,服務之間調用的簽名id。 *@param paramsMap,請求參數位置在Param中,以Key,Value的形式保存在HashMap中。 *@return RetEntity, 包含的錯誤碼信息。。 *@exception NA */ public static RetEntity httpGet(String url, String sessionId, String authId, Map<String, String> paramsMap) { return sendMessage(url, sessionId, authId, paramsMap, HttpMethod.GET); } public static RetEntity httpPost(String url, String sessionId, String authId, Map<String, String> paramsMap) { return sendMessage(url, sessionId, authId, paramsMap, HttpMethod.POST); } private static RetEntity sendMessage(String url, String sessionId, String authId, Map<String, String> paramsMap, HttpMethod httpMethod) { String httpUrl = url; //參數標誌,標記paramsMap是否爲空,0爲空。 int flag = MAP_EMPTY_FLAG; if (paramsMap != null && !paramsMap.isEmpty()) { String urlTmp = "?"; for(Entry<String, String> entry : paramsMap.entrySet()) { urlTmp = urlTmp + entry.getKey() + "=" + "{" + entry.getKey() + "}"; urlTmp = urlTmp + "&"; } int endIndex = urlTmp.lastIndexOf("&"); httpUrl = httpUrl + urlTmp.substring(0, endIndex); flag = MAP_NOT_EMPTY_FLAG; } //填充header數據及參數編碼格式,防止收到參數爲亂碼。 HttpHeaders requestHeaders = new HttpHeaders(); MediaType mediaType = MediaType.parseMediaType("application/json;charset=UTF-8"); requestHeaders.setContentType(mediaType); if (sessionId != null) { requestHeaders.add("sessionId", sessionId); requestHeaders.add("authId", authId); } HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<RetEntity> response = null; if (flag == MAP_NOT_EMPTY_FLAG) { response = restTemplate.exchange(httpUrl, httpMethod,requestEntity, RetEntity.class, paramsMap); } else { response = restTemplate.exchange(httpUrl, httpMethod, requestEntity, RetEntity.class); } RetEntity retValue = response.getBody(); return retValue; } }
返回類定義
package com.system.http.entity;
public class RetEntity <T>
{
private static final long serialVersionUID = 5451109092148890181L;
private int resultCode;
private T resultValue;
private String resultMsg;
public int getResultCode()
{
return resultCode;
}
public void setResultCode(int resultCode)
{
this.resultCode = resultCode;
}
public Object getResultValue()
{
return resultValue;
}
public void setResultValue(T resultValue)
{
this.resultValue = resultValue;
}
public String getResultMsg()
{
return resultMsg;
}
public void setResultMsg(String resultMsg)
{
this.resultMsg = resultMsg;
}
@Override
public String toString()
{
return "{" +
"resultCode=" + resultCode +
", resultValue=" + resultValue +
", resultMsg='" + resultMsg + '\'' +
'}';
}
}
方法調用測試類:
import com.system.http.entity.RetEntity;
import com.system.http.util.HttpSendUtils;
import java.util.HashMap;
import java.util.Map;
public class HttpUtilTmp
{
public static void main(String []args)
{
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("queryParam", "{\"startPage\":1,\"pageSize\":50}");
RetEntity retEntity = null;
retEntity = HttpSendUtils.httpGet("http://localhost:8085/userservice/v1/users/query",
"78d5cd86cb9d3caa3adfc7aa2ef221d03e4872dcceb1eb24c0d62be8a6f89366", "6",
paramMap);
}
}