java 调用在 URL 中有查询参数的“REST”服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14771043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Invoking a 'REST' service which have query parameters in the URL
提问by TJ-
I have to invoke a GET on a service which returns text/xml
.
我必须对返回的服务调用 GET text/xml
。
The endpoint is something like this:
端点是这样的:
http://service.com/rest.asp?param1=34¶m2=88¶m3=foo
When I hit this url directly on a browser (or some UI tool), all's good. I get a response.
当我直接在浏览器(或一些 UI 工具)上点击这个 url 时,一切都很好。我得到了回应。
Now, I am trying to use CXF WebClient
to fetch the result using a piece of code like this:
现在,我正在尝试使用CXF WebClient
这样的一段代码来获取结果:
String path = "rest.asp?param1=34¶m2=88¶m3=foo";
webClient.path(path)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_XML_TYPE)
.get(Response.class);
I was debugging the code and found that the request being sent was url encoded which appears something like this:
我正在调试代码,发现发送的请求是 url 编码的,看起来像这样:
http://service.com/rest.asp%3Fparam1=34%26param2=88%26param3=foo
Now, the problem is the server doesn't seem to understand this request with encoded stuff. It throws a 404. Hitting this encoded url on the browser also results in a 404.
现在,问题是服务器似乎不理解这个带有编码内容的请求。它会抛出 404。在浏览器上点击这个编码的 url 也会导致 404。
What should I do to be able to get a response successfully (or not let the WebClient encode the url)?
我应该怎么做才能成功获得响应(或不让 WebClient 对 url 进行编码)?
回答by Andre
Specify the parameters using the query method:
使用查询方法指定参数:
String path = "rest.asp";
webClient.path(path)
.type(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_XML_TYPE)
.query("param1","34")
.query("param2","88")
.query("param3","foo")
.get(Response.class);
回答by Romin
You will need to encode your URL. You can do it with the URLEncoder class as shown below:
您将需要对您的 URL 进行编码。您可以使用 URLEncoder 类来完成,如下所示:
Please replace your line
请更换您的线路
String path = "rest.asp?param1=34¶m2=88¶m3=foo";
with
和
String path = URLEncoder.encode("rest.asp?param1=34¶m2=88¶m3=foo");