-3

最初にログインする必要があるサーバー (最初の URL) があり、次に別の POST 要求 (2 番目の URL) を送信しますが、この投稿要求は、まだログオンしている場合にのみ実行できます。URL 2 を使用した POST リクエストをログに記録するにはどうすればよいですか?

コードは次のとおりです。

  HttpURLConnection con=(HttpURLConnection) new URL("http://Login(URL1)").openConnection();
            String headerName=null; String cookie=null; 
            for (int i=1; (headerName = con.getHeaderFieldKey(i))!=null; i++) {
                if (headerName.equals("Set-Cookie"))               
                 cookie = con.getHeaderField(i);            
            }
            cookie = cookie.substring(0, cookie.indexOf(";"));
            String cookieName = cookie.substring(0, cookie.indexOf("="));
            String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
            System.out.println(cookieName);
            System.out.println(cookieValue);
            con=(HttpURLConnection) new URL("http://Login(URL1)").openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Cookie", "session_id=" + cookieValue);
            con.setDoInput(true);
            con.setDoOutput(true);
            PrintWriter writer = new PrintWriter(con.getOutputStream());
            String account = "sdfsdf";
            String password = "sddfdsf";
            writer.println("&username=" + account + "&password=" + password + "&action=do_login&http=1");
            writer.close();

            System.err.println(con.getResponseCode());
            BufferedReader reader=new BufferedReader(new InputStreamReader(con.getInputStream()));
            String response;
            while ((response=reader.readLine())!=null) {
                System.out.println(response);
            }
            reader.close();


            con=(HttpURLConnection) new URL("http://POST Request URL").openConnection();
            con.setRequestMethod("POST")
4

2 に答える 2

-1

URL 2 への要求に資格情報を追加しようとしましたか?

UsernamePasswordCredentials creds = new UsernamePasswordCredentials(
            username, password);
request.addHeader(new BasicScheme().authenticate(creds, request));
HttpResponse response = httpClient.execute(request);
于 2013-06-19T15:28:03.453 に答える