Search code examples
httphttp-headersurl-encodinghtml-encode

HttpPost request including spaces fails


When using a HttpPost request I use UTF-8 for proper encoding. When I use a space in one of the parameters, I still get the following error:

Caused by: org.apache.http.ProtocolException: Invalid redirect URI: /seek/nearest.aspx?key=Miami vice&ex=0&cFilter=9a79e6ce-3344-409c-bbe9-496530baf758&children=n

The invalid character in the URL is the space between the "Miami" and "vice".

Hmmm, I thought that the POST request is not put in the URL string.

These are the steps I take to build the HttpPost request. In the "mKeyword" is the string with "Miami vice".

1 - put the request in the NameValue list:

List<NameValuePair> kwNvP = new ArrayList<NameValuePair>();
kwNvP.add(new BasicNameValuePair("ctl00$ContentBody$LocationPanel1$OriginText", mKeyword));

2 - build the URI

String search_url = "http://www.example.com/seek/nearest.aspx"; 
try {
    theUri = new URI( search_url);
} catch ( URISyntaxException e) { etc. 

3 - build the post request

HttpPost method = new HttpPost( theUri);
method.addHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0) Firefox/7.0");
method.addHeader("Pragma", "no-cache");
method.addHeader("Content-Type", "application/x-www-form-urlencoded");
method.addHeader("Accept-Language", "en");

4 - build the content entity

HttpEntity entity = null; 
try {
    entity = new UrlEncodedFormEntity( kwNvP, HTTP.UTF_8);
}
catch ( UnsupportedEncodingException e) { etc

5 - executing the request

method.setEntity( entity);
HttpResponse res2 = null;
try {
    Thread.sleep( (int) (1000 * GeoTools.random( 0.1, 0.3))); 
    res2 = client2.execute(method);
    Log.v( WaypointActivity.TAG, "Status line = " + String.valueOf(res2.getStatusLine()));
} catch (Exception e) { 
    // --> Coming here ... see the exception trace

Can you help me solving this problem?


Solution

  • Without seeing the complete program or the real target URL I'm not 100% sure ... but this part of the error stands out:

    Invalid redirect URI
    

    That implies that your original POST request is not returning a 200 but a 301, and whatever server is handling the redirect is creating the malformed URL, not your code.