记录我自己的工作
get 请求 ,携带 请求头 header (token)
url 根据参数 动态拼接
参数 放入 map 动态拼接
private String lclUrl = "http://xxx.xxxx.com/lcl";
private String TOKEN360FOB_URL = "http://xxx.xxxxxx.com/token?username={name}&password={password}";
public JSONObject get360fobToken() {
String json = restTemplate.getForObject(TOKEN360FOB_URL, String.class, username, password);
JSONObject json1 = JSONObject.fromObject(json);
return json1;
}
/**
* 拼箱
*
* @param departure
* @param departureDate
* @param destination
* @param destCountry
* @param lsps
* @param sortBy
* @param pageNum
* @param pageSize
* @return
*/
public JSONObject getLclFreight(String departure, String departureDate, String destination, String destCountry, String lsps, String sortBy, int pageNum, int pageSize) {
return this.getFclAndLcl(departure, departureDate, destination,
destCountry, lsps, sortBy, pageNum, pageSize, lclUrl);
}
/**
* 共同代码抽取
*
* @param departure
* @param departureDate
* @param destination
* @param destCountry
* @param lsps
* @param sortBy
* @param pageNum
* @param pageSize
* @param xxxUrl
* @return
*/
private JSONObject getFclAndLcl(String departure, String departureDate, String destination,
String destCountry, String lsps, String sortBy, int pageNum, int pageSize, String xxxUrl) {
JSONObject json = this.get360fobToken();
String t = json.getString("content");
String token = "Bearer " + t;
// 将token 放入请求头
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Authorization", token); //参数
Map<String, Object> uriVariables = new HashMap<String, Object>();
//拼接url
StringBuffer buffer = new StringBuffer();
buffer.append("?");
if (StringUtils.isNotBlank(departure)) {
buffer.append("departure={departure}").append("&");
uriVariables.put("departure", departure);
}
if (StringUtils.isNotBlank(departureDate)) {
buffer.append("departureDate={departureDate}").append("&");
uriVariables.put("departureDate", departureDate);
}
if (StringUtils.isNotBlank(destination)) {
buffer.append("destination={destination}").append("&");
uriVariables.put("destination", destination);
}
if (StringUtils.isNotBlank(destCountry)) {
buffer.append("destCountry={destCountry}").append("&");
uriVariables.put("destCountry", destCountry);
}
if (StringUtils.isNotBlank(lsps)) {
buffer.append("lsps={lsps}").append("&");
uriVariables.put("lsps", lsps);
}
if (StringUtils.isNotBlank(sortBy)) {
buffer.append("sortBy={sortBy}").append("&");
uriVariables.put("sortBy", sortBy);
} buffer.append("pageNum={pageNum}").append("&");
buffer.append("pageSize={pageSize}");
uriVariables.put("pageNum", pageNum);
uriVariables.put("pageSize", pageSize);
String url = xxxUrl + buffer.toString(); HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders); ResponseEntity<String> response =
restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class, uriVariables);
String resBody = response.getBody();
JSONObject temp = JSONObject.fromObject(resBody); return temp;
}
工作疑问:
可以用更简洁的方法 拼接 url 吗
个人qq : 332893400
AngDH.Lee