包含空格的HttpPost请求失败

时间:2015-01-01 11:07:17

标签: http http-headers url-encoding html-encode

使用HttpPost请求时,我使用UTF-8进行正确的编码。当我在其中一个参数中使用空格时,我仍然会收到以下错误:

引起:org.apache.http.ProtocolException:无效的重定向URI:/seek/nearest.aspx?key=Miami vice&amp; ex = 0&amp; cFilter = 9a79e6ce-3344-409c-bbe9-496530baf758&amp; children = n < / p>

网址中的无效字符是&#34; Miami&#34;之间的空格。和#34;副&#34;。

嗯,我以为POST请求没有放在URL字符串中。

这些是我构建HttpPost请求的步骤。在&#34; mKeyword&#34;是&#34; Miami Vice&#34;的字符串。

1 - 将请求放在NameValue列表中:

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

2 - 构建URI

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

3 - 构建帖子请求

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 - 构建内容实体

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

5 - 执行请求

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

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

如果没有看到完整的程序或真正的目标网址,我不是100%确定......但错误的这一部分很突出:

Invalid redirect URI

这意味着您的原始POST请求不会返回200但是301,并且处理重定向的任何服务器都会创建格式错误的URL,而不是您的代码。

相关问题