HttpClient 表单 URL 包含无值参数
需要传递不带值且不带“=”符号的 get 参数才能使用外部 API。 正如您所看到的, URL 的
http://example.com/Service/v1/service.ashx?methodName&name=val&blablabla
第一个参数是要在服务器上调用的方法的名称 (methodName),它没有任何值,也没有“=”。 我想以“正确”的方式形成参数,但目前形成如下所示:
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("name", "val"));
params.add(new BasicNameValuePair("name1", "val1"));
String paramString = URLEncodedUtils.format(params, "utf-8");
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(getEndpointUrl() + "?methodName&" + paramString);
问题出在最后一行,其中使用了串联(而不是参数的常规转换)。将“methodName”作为名称添加到 params 中,将 null 作为值添加到结果 URL 中,得到“methodName=”。服务器不理解这种表示法。
Need to pass get parameter without value and without "=" symbol to utilize external API. The URL is
http://example.com/Service/v1/service.ashx?methodName&name=val&blablabla
As you could see first parameter is the name of the method (methodName) to be called on the server and it does not have any value nor "=".
I want to form parameters in "right" way but at the moment forming them like below:
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("name", "val"));
params.add(new BasicNameValuePair("name1", "val1"));
String paramString = URLEncodedUtils.format(params, "utf-8");
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(getEndpointUrl() + "?methodName&" + paramString);
The problem is in last line where concatenation is used (instead of regular conversion of params). Adding "methodName" as name to params and null as value gives "methodName=" in resulting URL. Server does not understand such notation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您最好手动形成 URL。我们广泛使用 HttpGet 方法,并且当我们构造 URL 字符串时,我们手动这样做以确保参数的“正确性”。然后,我们使用 HttpClient 项目中的 URIUtil 对查询字符串进行编码:
I think you'd be better off forming the URL manually. We use HttpGet methods extensively, and when we construct URL strings, we do so manually to ensure parameter 'correctness'. We then use URIUtil from the HttpClient project to encode the query string:
最好查看 HttpClient 源代码。乍一看,您似乎需要子类化 HttpGet 并重写 getRequestLine 方法以返回 RequestLine 接口的实现,该接口将以适当的方式格式化 URL。
It's best to look through HttpClient sources. From the first sight it looks like you need to subclass HttpGet and override getRequestLine method to return your implementation of RequestLine interface that will format URL in appropriate way.
您可以输入一个虚假值而不在服务器上检查它。
You could put in a bogus value and not check it on the server.