gpt4 book ai didi

java - 删除传输编码 :chunked in the POST request?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:18 25 4
gpt4 key购买 nike

我正在使用以下代码发送一个 POST 请求,但该请求是以分块形式发送的(Transfer-Encoding: chunked)。我用谷歌搜索了这个问题,它说要包含 Content-Length 但在下面的代码中我不知道如何设置 Content-Length:

@RequestMapping(value = "/contacts", method = RequestMethod.POST)
public Map<String, ContactInfo> addContactInfo(
@RequestBody Map<String, ContactInfo> ContactInfoDto) {

ContactInfo contactInfo = ContactInfoDto.get("contact");
if (contactInfo == null) {
throw new IllegalArgumentException("Contact not found.");
}

contactInfo = this.contactInfoManager.addNew(contactInfo);
Map<String, ContactInfo> map = new HashMap<>();
map.put("contact", contactInfo);

return map;

}

最佳答案

您可以使用 ResponseEntity 显式设置 header 。棘手的一点是弄清楚您的内容实际有多长:

@RequestMapping(value = "/contacts", method = RequestMethod.POST)
public ResponseEntity<Map<String, ContactInfo>> addContactInfo(@RequestBody Map<String, ContactInfo> contactInfoDto) throws JsonProcessingException {

ContactInfo contactInfo = contactInfoDto.get("contact");
if (contactInfo == null) {
throw new IllegalArgumentException("Contact not found.");
}

contactInfo = this.contactInfoManager.addNew(contactInfo);
Map<String, ContactInfo> map = new HashMap<>();
map.put("contact", contactInfo);

HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_LENGTH, String.valueOf(new ObjectMapper().writeValueAsString(map).length()));
return new ResponseEntity<Map<String, ContactInfo>>(map, headers, HttpStatus.CREATED);
}

测试:

$ curl -v http://localhost:8080/contacts/ -X POST -d '{ "contact": { "name": "foo" } }' -H 'Content-Type: application/json' && echo
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> POST /contacts/ HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Type: application/json
> Content-Length: 32
>
* upload completely sent off: 32 out of 32 bytes
< HTTP/1.1 201 Created
< Server: Apache-Coyote/1.1
< X-Application-Context: application
< Content-Type: application/json;charset=UTF-8
< Content-Length: 26
< Date: Fri, 10 Jun 2016 13:24:23 GMT
<
* Connection #0 to host localhost left intact
{"contact":{"name":"foo"}}

关于java - 删除传输编码 :chunked in the POST request?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35200216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com