Java/Apache HttpClient无法处理带有竖线/管道符的URL。

12

如果我想处理这个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");

那个方法效果不太好。

有什么建议可以让这个方法生效吗?

5个回答

11

2
这是正确的。编码整个字符串会失败,因为URI无法识别已编码的“http://”。 - Sotirios Delimanolis

10

你必须将URL中的|编码为%7C

考虑使用HttpClient的URIBuilder,它会自动处理转义字符,例如:

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);

这个答案比Tarsem的答案更详细,但有助于了解URI中有哪些部分。另一方面,它将处理和编码保持在URIBuilder的实现细节中,使其更加隐蔽。 - Oliver

1

我曾经遇到同样的问题,我通过将 | 替换为其编码值 => %7C 并解决了它,现在它可以正常工作。

从这里开始

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

转换为这个

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

0
在post中,我们不会将参数附加到URL上。下面的代码会添加并对您的参数进行url编码。它取自:http://hc.apache.org/httpcomponents-client-ga/quickstart.html
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://testurl.com/lists/lprocess");

    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("action", "LoadList|401814|1"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    HttpResponse response2 = httpclient.execute(httpPost);

    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed

        String response = new Scanner(entity2.getContent()).useDelimiter("\\A").next();
        System.out.println(response);


        EntityUtils.consume(entity2);
    } finally {
        httpPost.releaseConnection();
    }

引用:“在帖子中,我们不将参数附加到url上。”这是不正确的。您可以使用URL参数在POST请求中发送数据,并且它不会与任何标准冲突。 - Oliver

0

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接