2017-03-20 80 views
1

我正在處理一個API,我需要在POST請求中提供JSON數組作爲查詢參數。報價必須在網址中,但OkHttp和HttpURL不斷將其轉換爲%22。該API不會識別這個並返回一個錯誤代碼。如何讓OkHttp保留請求中的引用。我處理看起來像這樣的代碼:如何使用OkHttp保留雙引號

public static void post(String url, String[][] requestParams, Callback callback) { 
    HttpUrl httpUrl = addParamsToURL(getAbsoluteUrl(url), requestParams); 


    Request request = new Request.Builder() 
      .url(httpUrl) 
      .addHeader("app", Prefs.getString(Constants.HEADER_APP, null)) 
      .addHeader("authoToken", Prefs.getString(Constants.HEADER_AUTH_TOKEN, null)) 
      .post(RequestBody.create(MediaType.parse("application/json"), "")) 
      .build(); 
    okHttpClient.newCall(request).enqueue(callback); 
} 

private static HttpUrl addParamsToURL(String url, String[][] requestParams) { 
    HttpUrl httpUrl = HttpUrl.parse(url); 
    HttpUrl.Builder urlBuilder = httpUrl.newBuilder(); 
    for(int i = 0, size = requestParams.length; i < size; i++) { 
     urlBuilder.addEncodedQueryParameter(requestParams[i][0], requestParams[i][1]); 
    } 
    return urlBuilder.build(); 
} 

我需要的URL的請求轉到看起來像https://www.baseurl.com/path?queryName=["[email protected]"]而是它看起來像https://www.baseurl.com/path/?queryName=[%[email protected]%22]

回答

1

雖然,你應該認真考慮什麼Jesse Wilson說,但作爲一種解決方法,你可以看到人們有什麼建議在這些線程中做:

特別是Mike Nakhimovich suggests更換編碼字符後面通過攔截器:

request.url(originalRequest.url().toString().replace("%3D","=")); 
+1

它進一步證明,問題是_not_的雙引號,但是是一個錯字了線。不過,我知道這對許多服務器設置不佳的人來說是個問題,所以我正在選擇你的答案。 – drawinfinity

2

修復服務器。 OkHttp與所有在查詢字符串中編碼"%22的網頁瀏覽器一致。

鉻:

GET /?a=[%[email protected]%22] HTTP/1.1 
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 

火狐:

GET /?a=[%[email protected]%22] HTTP/1.1 
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.0) Gecko/20100101 Firefox/52.0 

Safari瀏覽器

GET /?a=[%[email protected]%22] HTTP/1.1 
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8