1. 程式人生 > >Java - 使用RestTemplate代理Http請求

Java - 使用RestTemplate代理Http請求

使用RestTemplate代理Http請求(請求方式不限),下面對POST請求的Body進行了封裝。
HttpEntity:請求實體。
封裝Body還可以用MultiValueMap。
public ResponseEntity<byte[]> proxy(String prefix, HttpEntity<String> httpEntity, HttpServletRequest req) {
    String query = req.getQueryString();
    String url = commonMappingConfig.getUrlprefixmap().get(prefix) + req.getRequestURI();
    if (query != null) {
        url = url + "?" + query;
    }
    String subReqStr = httpEntity.getBody();
    SugReq subReq = JSONObject.parseObject(subReqStr, SugReq.class);
    subReq.setAccessToken(accessToken);
    HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(subReq), httpEntity.getHeaders());
    return restTemplate.exchange(url, HttpMethod.POST, formEntity, byte[].class);
}