11

如果我想处理这个网址,例如:

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

^ 那也不行。

任何建议如何使这项工作?

4

5 回答 5

11

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

于 2013-08-19T14:31:23.883 回答
9

|您必须在 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);
于 2013-08-19T14:26:36.770 回答
1

我有同样的问题,我解决了它替换 | 对于它的编码值 => %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");
于 2017-05-19T09:10:54.937 回答
0

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

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

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

于 2013-08-19T14:30:41.020 回答
0

在帖子中,我们不会将参数附加到 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();
    }
于 2013-08-19T14:56:36.893 回答