2017-06-14 10 views
0

私は1つの残りのURLを打つ必要があり、その前に私はusername/passwordを渡すことによってloginn目的の別の休憩URLを打っています。私は最初のURLから200 OKを得ています。今、私は「同じセッション内で複数のURLを打つ方法とJavaで1つの認証を使用する

String urlParameters = "username=a&password=b&rememberme=false"; 
    byte[] postData  = urlParameters.getBytes(StandardCharsets.UTF_8); 
    int postDataLength = postData.length; 
    URL url = new URL("myloginurl"); 
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
    con.setDoOutput(true); 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    con.setRequestProperty("charset", "UTF-8"); 
    con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 
    con.setUseCaches(false); 
    try(DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { 
     wr.write(postData); 
    } 
    int respCode = con.getResponseCode(); 
    if(respCode==200){ 
     urlParameters = "id=x&col1=y&op1=z&val1=t"; 
     postData  = urlParameters.getBytes(StandardCharsets.UTF_8); 
     postDataLength = postData.length; 
     url = new URL("myanotherurl"); 
     con.setDoOutput(true); 
     con = (HttpURLConnection) url.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     con.setRequestProperty("charset", "UTF-8"); 
     con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); 
     con.setUseCaches(false); 
     try(DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { 
      wr.write(postData); 
     } 
     System.out.println(con.getResponseCode()); 
    } 

誰もが私がミスをやっているところを指摘してくださいすることができ、次のようにそれは私に401 error.Codeを与えている別のREST URLは消費しようとしていたときに。また、私が知っているように任意のより良い方法はありこのコードを記述します。サーバーが最初の要求で新しいクッキーの形でセッションIDを返す必要があります

答えて

0

ありがとうございました。サーバーがユーザーを識別できるように、あなたは、あなたの2番目のリクエストでそのクッキーを含める必要がありますCookieはhttpヘッダー内で送信されます。

あなたが最初の要求からはResponseCodeを取得した後、あなたのような新しいクッキー値フェッチすることができます

String cookieValue = con.getHeaderFields() 
    .getOrDefault("Set-Cookie", Collections.emptyList()) 
    .stream() 
    .map(str -> str.split(";")[0]) 
    .collect(joining("; ")); 

を次に、あなたは次のように次の要求でCookieのためにその値を使用:

con.setRequestProperty("Cookie", cookieValue); 
+0

ことができますしてくださいいくつかのコードで助けてください。 – Manish

+0

collect(joined( ";")) – Manish

+0

これはコレクタの静的メソッドであり、複数のクッキー値を '; 'をセパレータとして使用します。より多くのSet-Cookieヘッダーフィールドがある場合に使用されます。 – rainerhahnekamp

関連する問題