如何使用OkHttp保留双引号

时间:2017-03-20 19:09:50

标签: android okhttp okhttp3

我正在处理一个api,我需要在POST请求中提供一个JSON数组作为查询参数。报价必须在网址中,但OkHttp和HttpURL会将其转换为%22。 API将无法识别此并返回错误代码。如何让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();
}

我需要请求的网址看起来像https://www.baseurl.com/path?queryName=["email@domain.com"],但它看起来像https://www.baseurl.com/path/?queryName=[%22email@domain.com%22]

2 个答案:

答案 0 :(得分:2)

修复服务器。 OkHttp与在浏览器字符串中编码"%22的Web浏览器一致。

铬:

GET /?a=[%22email@domain.com%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=[%22email@domain.com%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=[%22email@domain.com%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

答案 1 :(得分:1)

虽然,你应该强烈考虑Jesse Wilson所说的内容,但作为一种解决方法,你可以看到人们建议在这些主题中做些什么:

特别是,Mike Nakhimovich suggests通过拦截器替换编码字符:

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