2017-04-07 70 views
3

當我使用郵差,我收到正確的響應(服務器進程「類別」作爲陣列)使用以下請求描述從服務器: Postman request body使用Volley在POST請求中發送數組的正確方法是什麼?

與標頭: Postman request headers

該請求具有這種原始代表:

POST /api/items HTTP/1.1 
Host: www1. 
Content-Type: application/x-www-form-urlencoded 
Cache-Control: no-cache 
Postman-Token: c18f92ee-2f36-f4dd-2963-6bc6d1db0bdf 

items=247642&categories%5B%5D=12&categories%5B%5D=11 

我的問題是如何表示描述的請求,以正確使用Volley庫發射它。我試過很多變種,比如:

@Override 
public byte[] getBody() throws AuthFailureError { 
    return "items=247642&categories%5B%5D=12".getBytes(); 
} 

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    Map<String,String> headers = super.getHeaders(); 
    headers.put("Content-Type", "application/x-www-form-urlencoded"); 
    return headers; 
} 

但他們要麼都不編碼「類別」爲陣列(這樣服務器不參與帳戶在所有這些變量)或作出不正確的方式編碼,所以服務器無法獲得這個數組的值。

UPDATE:

我只是試着用OkHttp火這一要求,這是絕對正確的(如與情況郵差以上):

MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); 
      RequestBody body = RequestBody.create(mediaType, "items=247642&categories%5B%5D=10&categories%5B%5D=9"); 
      Request request = new Request.Builder() 
        .url("http://www1...") 
        .post(body) 
        .addHeader("content-type", "application/x-www-form-urlencoded") 
        .addHeader("cache-control", "no-cache") 
        .build(); 

這意味着只有一件事:Volley以其他方式處理原始請求體(可能是不正確的),或者Volley中存在一些微妙的配置,無法正確執行這些請求。

回答

0

我應該承認問題中所描述的問題大多是基於服務器的邏輯。通過傾倒來自Volley和OkHttp的請求組織並逐步比較它們,我可以發現它們僅在一個頭部中有區別 - Content-Type。在OkHttp它看起來像:

Content-Type: application/x-www-form-urlencoded; charset=utf-8 

,而在排球是:

Content-Type: application/x-www-form-urlencoded, application/x-www-form-urlencoded; charset=UTF-8 

所以看起來它是一種在服務器上的標題的嚴格檢查。爲了讓排球的頭等於OkHttp的,我不得不刪除getHeaders()方法的重載的請求,並在getBodyContentType()方法返回身型描述:

@Override 
public String getBodyContentType() { 
    return "application/x-www-form-urlencoded"; 
} 

我不能說,我的問題是完全解決,因爲有仍然可以有更多關於如何使用更優雅的方式在POST請求體中添加數組的答案(沒有原始主體和其他格式 - 例如JSON)。

相關問題