改造无效的URI

时间:2015-09-05 20:57:29

标签: java retrofit

您好我试图通过Retrofit进行简单的http get查询。

我的参数有一些特殊字符,似乎网址编码失败。

原件:

data=[out:json];node["name"~"Karlsruhe"]["place"~"city|village|town"];out body;

正确的编码应如下所示:

data=%5Bout%3Ajson%5D%3Bnode%5B%22name%22~%22Karlsruhe%22%5D%5B%22place%22~%22city%7Cvillage%7Ctown%22%5D%3Bout%20body%3B

但Retrofit创造了这个:

data=[out:json];node[%22name%22~%22Karlsruhe%22][%22place%22~%22city|village|town%22];out%20body;

这将失败:

  

java.lang.IllegalStateException:无效为java.net.URI:   http://overpass.osm.rambler.ru/cgi/interpreter?data=[out:json];node[%22name%22~%22Karlsruhe%22][%22place%22~%22city|village|town%22];out%20body;     在com.squareup.okhttp.HttpUrl.uri(HttpUrl.java:336)at   com.squareup.okhttp.internal.http.RouteSelector.resetNextProxy(RouteSelector.java:135)     在   com.squareup.okhttp.internal.http.RouteSelector。(RouteSelector.java:71)     在   com.squareup.okhttp.internal.http.RouteSelector.get(RouteSelector.java:76)     在   com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:321)     在   com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:245)     在com.squareup.okhttp.Call.getResponse(Call.java:267)at   com.squareup.okhttp.Call $ ApplicationInterceptorChain.proceed(Call.java:224)     在   com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:195)     在com.squareup.okhttp.Call.execute(Call.java:79)at   retrofit.OkHttpCall.execute(OkHttpCall.java:112)

可以在此处解决此编码问题? 感谢

1 个答案:

答案 0 :(得分:8)

我不确定编码错误的根本原因是什么,但您可以使用encoded符号来处理true参数。将参数设置为encoded=true会告诉我们已经对参数进行了编码,因此请不要再次编码。

在您的服务界面中,将@Query添加到您的Call<ResponseBody> getResponse(@Query(value = "data", encoded = true) String data); 注释中。像 -

这样的东西
final String encodedData = URLEncoder.encode(data, "UTF-8");
Call<ResponseBody> result = service.getResponse(encodedData);

然后,在发送改造之前自己编码参数。

{{1}}