2015-09-28 258 views
0

为什么下面的代码打印“Method:GET”而不是“Method:POST”?将POST请求视为GET请求

我需要它以编程方式授权http://www.havenandhearth.com/portal/

public class Main { 

    public static void main(String[] args) { 

     try { 
      URL url = new URL("http://www.havenandhearth.com/portal/sec/login"); 
      HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 

      String parameters = "username=xxx&password=yyy"; 

      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      conn.setRequestProperty("Content-Length", String.valueOf(parameters.length())); 

      conn.setDoOutput(true); 
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 
      wr.writeBytes(parameters); 
      wr.flush(); 
      wr.close(); 

      int responsecode = conn.getResponseCode(); 
      if (responsecode != HttpURLConnection.HTTP_OK) { 
       System.out.println("Unable to make POST request. Response code: " + responsecode); 
       return; 
      } 

      System.out.println("Method: " + conn.getRequestMethod()); 
     } catch (IOException ex) { 
      System.out.println("Error: " + ex.getMessage()); 
     } 
    } 
} 

如果我将URL更改为http://httpbin.org/post,它按预期工作。

为了实现目标,您需要将xxx和yyy替换为实际的帐户凭据。

在此先感谢。

+0

当我运行你的代码,我看到这个结果:'方法:POST' –

+0

@David Herrero啊,这是因为无效的帐户凭据,对不起 – FrozenHeart

+1

好吧,我认为,当您使用您的凭据成功的POST,网页将您重定向到主页,所以conn现在发出GET请求。 –

回答

0

这似乎是由于自动重定向。

如果我设置

conn.setInstanceFollowRedirects(false); 

它按预期工作。

+1

是的,你是对的,你回答了你自己的问题!哈哈,恭喜 PD:我从来没有听说过那个游戏......看起来有趣 –

+0

@David Herrero是的,你应该看看它 – FrozenHeart