HttpPost - >重定向 - >需要的地点或机构

时间:2011-11-04 19:54:50

标签: java android http-post httpresponse http-status-code-302

这是将数据POST到网站而不是作为响应重定向的Java代码(状态302)。它在我的PC(Eclipse,Java,Ubuntu)上完美运行,它完全符合我的要求。

我尝试了很多东西来发布代码功能,但我无法做到。

Java代码:

// Preparing the CLIENT and POST Method
  HttpClient httpclient = new DefaultHttpClient();
  HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");

  try {
     // Add your POST METHOD attributes
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
     nameValuePairs.add(new BasicNameValuePair("op", "Search"));
     nameValuePairs.add(new BasicNameValuePair("player", "Jaiybe"));
     nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
     nameValuePairs.add(new BasicNameValuePair("form_build_id",
           "form-526370b788622996caa3669e7b975ccf"));
     nameValuePairs.add(new BasicNameValuePair("form_id",
           "ladders_filter_form"));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     // Execute HTTP Post Request
     HttpResponse response = httpclient.execute(httppost);

     // RESPONE THAT WORKS WITH JAVA
     System.out.println("Location:");
     String LocationHeader = response.getFirstHeader("location").getValue();
     System.out.println(LocationHeader);
     System.out.println();

     // To get the BODY I would have to parse that again - since its not REDIRECTING automatically
     HttpClient httpclient2 = new DefaultHttpClient();
     HttpPost httppost2 = new HttpPost(LocationHeader);
     response = httpclient2.execute(httppost2);
     System.out.println("And EVEN the response body:");
     System.out.println(EntityUtils.toString(response.getEntity()));

代码确实:

  1. 帖子
  2. 获取重定向 - 获取位置标题
  3. 解析位置
  4. 我需要android来做同样的事情。无论是“位置”还是回复体,都可以,我不需要两者。

    帖子:http://www.anddev.org/networking-database-problems-f29/httppost-clientprotocolexception-t56118.html

3 个答案:

答案 0 :(得分:2)

我找到了问题!

httpclient.getParams().setParameter("http.protocol.version",
                HttpVersion.HTTP_1_0);

只需更改这一行 - 版本1_0可以正常工作,而1_1则不行。不要问我为什么:)

谢谢大家!

答案 1 :(得分:2)

请尝试以下代码。缺少标头中的位置,因为页面已经重定向。因此,我们可以禁用重定向以获取位置标记。

httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);

答案 2 :(得分:0)

尝试在创建http客户端后调用此方法,使其跟随重定向

httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);