Cannot process url with vertical/pipe bar in Java/Apache HttpClient

最后都变了- 提交于 2019-12-23 07:39:15

问题


If I want to process this url for example:

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

Java/Apache won't let me because it says that the vertical bar ("|") is illegal.

escaping it with double slashes doesn't work as well:

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

^ that doesn't work as well.

Any suggestions how to make this work?


回答1:


try with URLEncoder.encode()

Note: you should encode string which is after action= not complete URL

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

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




回答2:


You must encode | in a URL as %7C.

Consider using HttpClient's URIBuilder which takes care of the escaping for you, e.g.:

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



回答3:


I had same problem and I solve it replacing the | for a encoded value of it => %7C and ir works

From this

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

To this

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



回答4:


You can encode URL parameters using the URLEncoder:

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

This will encode all special characters, not just the pipe, for you.




回答5:


In post we don't attach parameters to url. Code below adds and urlEncodes your parameter. It's taken from: 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();
    }


来源:https://stackoverflow.com/questions/18316242/cannot-process-url-with-vertical-pipe-bar-in-java-apache-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!