删除Transfer-Encoding:在POST请求中分块? [英] Remove Transfer-Encoding:chunked in the POST request?

查看:175
本文介绍了删除Transfer-Encoding:在POST请求中分块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码发送 POST 请求,但请求以chunked的形式发送( Transfer-Encoding:chunked )。我用Google搜索了问题并说它包含了 Content-Length 但是在下面的代码中我无法弄清楚如何设置 Content-长度

I am sending a POST request using the following code but the request is send in the form of chunked (Transfer-Encoding: chunked). I googled about the problem and it says to include the Content-Length but in the below code I could not figure out how could I set the 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 显式设置标头。棘手的一点是弄清楚你的内容实际有多长:

You can use ResponseEntity to set headers explicitly. The tricky bit is figuring out how long your content actually is:

@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"}}

这篇关于删除Transfer-Encoding:在POST请求中分块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆