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

时间:2013-08-19 14:24:06

标签: java apache apache-httpclient-4.x apache-commons-httpclient

如果我想处理此网址,例如:

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 个答案:

答案 0 :(得分:10)

尝试使用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

答案 1 :(得分:8)

您必须将|中的%7C编码为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);

考虑使用HttpClient的URIBuilder来处理你的转义,例如:

{{1}}

答案 2 :(得分:0)

您可以使用URLEncoder

对网址参数进行编码
post = new HttpPost("http://testurl.com/lists/lprocess?action=" + URLEncoder.encode("LoadList|401814|1", "UTF-8"));

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

答案 3 :(得分:0)

在帖子中,我们不会将参数附加到网址。下面的代码添加并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();
    }

答案 4 :(得分:0)

我有同样的问题,我解决了它取代了|对于它的编码值=&gt; %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");