2011-04-03 68 views
11

我試圖發送帶有Cookie的發佈請求。這是代碼:Java HttpURLConnection - POST與Cookie

try { 

    String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8"); 
    String cookies = "session_cookie=value"; 
    URL url = new URL("https://myweb"); 
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 

    conn.setRequestProperty("Cookie", cookies); 
    conn.setRequestMethod("POST"); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 

    DataOutputStream out = new DataOutputStream(conn.getOutputStream()); 
    out.writeBytes(query); 
    out.flush(); 
    out.close(); 

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String decodedString; 
    while ((decodedString = in.readLine()) != null) { 
     System.out.println(decodedString); 
    } 
    in.close(); 

    // Send the request to the server 
    //conn.connect(); 
} catch (MalformedURLException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

問題是請求發送沒有cookie。如果我只製作: conn.connect();並且不發送數據,cookies發送OK。 我不能確切地檢查發生了什麼,因爲連接通過SSL。我只檢查迴應。

回答

6

按照URLConnection的javadoc:

The following methods are used to access the header fields and the 
contents AFTER the connection is made to the remote object: 

* getContent 
* getHeaderField 
* getInputStream 
* getOutputStream 

你有沒有證實,在你的測試用例請求以上越來越到服務器呢?我看到你在getOutputStream()之後撥打了connect(),並且發表了評論。如果您取消註釋並在撥打getOutputStream()之前向上移動,會發生什麼情況?

+0

謝謝!我再次嘗試在服務器中重寫php代碼,並且它工作得很完美。我發佈的代碼是OK的。我認爲問題出在服務器上(我可能寫了$ _POST [$ key]而不是$ _POST ['key']或類似的東西..)。 – Alberto 2011-04-05 14:04:29

相關問題