大部分时间都是'Content-Type': 'application/json',flask_appbuilder的服务中很多接口是 multipart/form-data;,
用python调用时,通常情况下
data = json.dumps({ "catalogCode":"region","pageNo": 1, "pageSize": 1000})
headers = {'Token': Token, 'Accept': 'application/json', 'Content-Type': 'application/json;charset=utf-8'}
r = requests.post(user_url, headers=headers, data=data)```
form-data时需要如下
data ={ "catalogCode":"region","pageNo": 1, "pageSize": 1000} headers = {'Token': Token}
r = requests.post(user_url, headers=headers, data=data)
但是在java中,不只是改为'Content-Type': 'multipart/form-data'
还需要用MultiValueMap
```java
HttpEntity entity = new HttpEntity(req.getRequestBody(), headers);
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ResponseEntity response = restTemplate.exchange(url, httpMethod, entity, respTypes)
if (response != null) {
int status = response.getStatusCode().value();
rsp.setStatus(status);
HttpHeaders rspHeaders = response.getHeaders();
if (rspHeaders != null) {
Map<String, String> rspHeaderMap = new HashMap<>(8);
for (Map.Entry<String, List<String>> entry : rspHeaders.entrySet()) {
rspHeaderMap.put(entry.getKey(), entry.getValue().toString());
}
rsp.setHeader(rspHeaderMap);
}
rsp.setBody(response.getBody());```
这里要改为
```java
LinkedHashMap linkedHashMap= (LinkedHashMap)req.getRequestBody();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
Iterator it = linkedHashMap.entrySet().iterator();
while (it.hasNext()){
Map.Entry entry = (Map.Entry)it.next();
map.add((String)entry.getKey(),entry.getValue());
}
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);
// HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
ParameterizedTypeReference<BaseResponse> respTypes = new ParameterizedTypeReference<BaseResponse>() {};
try {
RestTemplate rt = new RestTemplate();
BaseResponse response =rt.postForObject("http://127.0.0.1:8550/edit/12",
entity, BaseResponse.class);```
标签:HttpEntity,entity,headers,参数,new,data,response
From: https://www.cnblogs.com/bigleft/p/18159844