无法在Java/Apache HttpClient中处理带有垂直/管道栏的url



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

^那不太管用。

有什么建议吗?

尝试URLEncoder.encode()

注意:您应该编码action=之后的字符串,而不是complete URL

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

参考http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html

您必须将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);

我遇到了同样的问题,我解决了这个问题,将|替换为它的编码值=>%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");

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

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

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

在帖子中,我们不将参数附加到url。下面的代码添加并urlEncodes您的参数。它取自: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();
    }

最新更新