在Retrofit中进行form-urlencoded Get请求时,如何避免请求参数名称被编码?

时间:2018-01-22 22:22:48

标签: android retrofit urlencode okhttp3

我目前正在开发使用Retrofit& amp; OkHttpClient从服务器获取/发送数据。 这在调用我自己的服务器时非常棒,而在尝试调用google map api时遇到404错误。

以下表示有错误的响应。 cuCtxSetCurrent(sameCtx)

这显然是因为'/'和'?'被编码为“%2F”和“%3F”。 该解决方案可能会阻止这些特殊字符的urlencode,但无法实现。

我尝试的是通过intercepter向OkHttpClient添加自定义标题“Content-Type:application / x-www-form-urlencoded; charset = utf-8”,但这不起作用。

最好的详细回复将不胜感激。

问候。


Response{protocol=h2, code=404, message=, url=https://maps.googleapis.com/maps%2Fapi%2Fgeocode%2Fjson%3Fkey=defesdvmdkeidm&latlng=11.586215,104.893197}

1 个答案:

答案 0 :(得分:0)

问题在于您的Retrofit服务界面的定义以及您传递给它的值。

public interface DenningService {
    @GET("{url}")
    @Headers("Content-Type:application/x-www-form-urlencoded; charset=utf-8")
    Single getEncodedRequest(@Path("url") String url);
}

根据您发布的内容,我将假设url的值为:

maps/api/geocode/json?key=defesdvmdkeidm&latlng=11.586215,104.893197

以下是它的外观:

public interface DenningService {
    @FormUrlEncoded
    @GET("/maps/api/geocode/json")
    Single getEncodedRequest(@Field("key") String key,
                             @Field("latlng") String latlng);
}

然后你会这样称呼它:

mSingle = getGoogleService().getEncodedRequest(key, latlng);

当然,您必须弄清楚如何将keylatlng参数与当前url字符串分开。

修改

对我来说,您实际上想要您的请求是application/x-www-form-urlencoded,或者您是否只是尝试查看它是否解决了您的问题,这一点并不明显。如果你想要它,那么你的界面将会是这样的:

public interface DenningService {
    @GET("/maps/api/geocode/json")
    Single getEncodedRequest(@Query("key") String key,
                             @Query("latlng") String latlng);
}