无法在Java/Apache HttpClient中使用垂直/管道栏处理url

无法在Java/Apache HttpClient中使用垂直/管道栏处理url,java,apache,apache-httpclient-4.x,apache-commons-httpclient,Java,Apache,Apache Httpclient 4.x,Apache Commons Httpclient,如果我想处理此url,例如: post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList|401814|1"); Java/Apache不允许我这样做,因为它说竖条(“|”)是非法的 用双斜杠转义也不管用: post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList\\|401814\\|1"); ^那也不行 有什么建议吗?您必须

如果我想处理此url,例如:

post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList|401814|1");
Java/Apache不允许我这样做,因为它说竖条(“|”)是非法的

用双斜杠转义也不管用:

post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList\\|401814\\|1");
^那也不行


有什么建议吗?

您必须在URL中将
|
编码为
%7C

考虑使用HttpClient,它为您提供转义服务,例如:

final URIBuilder builder = new URIBuilder();
builder.setScheme("http")
    .setHost("testurl.com")
    .setPath("/lists/lprocess")
    .addParameter("action", "LoadList|401814|1");
final URI uri = builder.build();
final HttpPost post = new HttpPost(uri);

您可以使用以下代码对URL参数进行编码:


这将为您编码所有特殊字符,而不仅仅是管道。

尝试使用
URLEncoder.encode()

注意:您应该对
操作=
之后的字符串进行编码,而不是
完整URL

post = new HttpPost("http://testurl.com/lists/lprocess?action="+URLEncoder.encode("LoadList|401814|1","UTF-8"));

参考

在文章中,我们不会将参数附加到url。下面的代码添加参数并对其进行URL编码。它取自:

DefaultHttpClient-httpclient=newdefaulthttpclient();
HttpPost HttpPost=新的HttpPost(“http://testurl.com/lists/lprocess");
List-nvps=newarraylist();
添加(新的BasicNameValuePair(“操作”,“加载列表| 401814 | 1”));
setEntity(新的UrlEncodedFormEntity(nvps));
HttpResponse response2=httpclient.execute(httpPost);
试一试{
System.out.println(response2.getStatusLine());
HttpEntity entity2=response2.getEntity();
//对响应体执行一些有用的操作
//并确保它被完全消耗
字符串响应=新扫描程序(entity2.getContent()).useDelimiter(“\\A”).next();
System.out.println(响应);
EntityUtils.consume(entity2);
}最后{
httpPost.releaseConnection();
}

我也遇到了同样的问题,我解决了这个问题,将|替换为它的一个编码值=>%7C和ir起作用

由此

post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList|401814|1");
对此

post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList\\%7C401814\\%7C1");

这是正确的。对整个字符串进行编码将失败,因为URI无法识别编码的
http://
。这个答案比其他答案更详细,但有助于了解URI中有哪些部分。另一方面,它将处理和编码很好地隐藏在
URIBuilder
的实现细节中。引用:“在post中,我们不将参数附加到url。”这是不正确的。您可以很好地使用URL参数在POST请求中发送数据,并且不会与任何标准发生冲突。
post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList|401814|1");
post = new HttpPost("http://testurl.com/lists/lprocess?action=LoadList\\%7C401814\\%7C1");