如何使用HttpURLConnection进行2次POST请求

时间:2017-04-12 21:12:28

标签: java http cookies request httpurlconnection

我需要通过java应用程序浏览网站。

登录后我需要调用表格。

我的代码是:

String url = "http://xxxxxx.net:1900/login";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setReadTimeout(5000);
        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "username=myusername&password=mypsw";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        String headerName=null;
        String cookie="";
        for (int i=1; (headerName = con.getHeaderFieldKey(i))!=null; i++) {
           if (headerName.equals("Set-Cookie")) {                  
             cookie = con.getHeaderField(i);  
           }
        }
        //print my cookie
        System.out.println("PRIMO COOKIE "+ cookie);

然后我需要调用提交表单... 我使用这段代码:

String url = "http://xxxx.net:1910/myrequest";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setReadTimeout(5000);
        //add reuqest header
        con.setRequestProperty("Host", "http://xxxx.net:1910");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept","*/*");
        con.setRequestProperty("Accept-Language", "it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4");
        con.setRequestProperty("Cookie", c);  //c is String of my cookie
        con.setRequestProperty("Connection", "keep-alive");

        int responseCode = con.getResponseCode();
        String headerName=null;


        String cookie="";
        for (int i=1; (headerName = con.getHeaderFieldKey(i))!=null; i++) {
           if (headerName.equals("Set-Cookie")) {                  
             cookie = con.getHeaderField(i);  //    <--- the cookie is empty. why?
           }
        }
        System.out.println("SECONDO COOKIE "+ cookie);

为什么当我的第二次请求再次需要登录? 为什么第二个cookie是空的?

祝你好运

0 个答案:

没有答案