簡體   English   中英

刪除Transfer-Encoding:在POST請求中分塊?

[英]Remove Transfer-Encoding:chunked in the POST request?

我使用以下代碼發送POST請求,但請求以chunked( 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顯式設置標頭。 棘手的一點是弄清楚你的內容實際有多長:

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

以下代碼:

@RequestMapping(value = "/contacts", method = RequestMethod.POST)
public Map<String, ContactInfo> addContactInfo(
                                @RequestBody Map<String, ContactInfo> ContactInfoDto,    
                                @RequestHeader(value = HttpHeaders.CONTENT_LENGTH, required = true) Long contentLength
) { ... }

可用於要求發送Content-Length標頭。 請注意,您還必須在發送請求的代碼中添加該標頭(大多數客戶端會自動執行此操作但更好地檢查)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM