不介绍太多,只介绍实用的,像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);
}
}