2011-04-03 13 views
11

के साथ पोस्ट करें मैं कुकीज़ के साथ एक पोस्ट अनुरोध भेजने की कोशिश कर रहा हूं। यह कोड है:जावा HttpURLConnection - कुकी

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(); 
} 

समस्या यह है कि अनुरोध कुकीज़ के बिना भेजा जाता है। अगर मैं केवल: conn.connect(); और डेटा नहीं भेजते हैं, कुकीज़ ठीक से भेजे जाते हैं। मैं यह नहीं देख सकता कि वास्तव में क्या हो रहा है, क्योंकि कनेक्शन एसएसएल है। मैं केवल प्रतिक्रिया की जांच करता हूं।

उत्तर

6

URLConnection जावाडोक के अनुसार:

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 कोड को फिर से लिखने की कोशिश की, और यह सही काम किया। मेरे द्वारा पोस्ट किया गया कोड ठीक था। मुझे लगता है कि समस्या सर्वर में थी (क्या मैंने $ _POST ['key'] के बजाय $ _POST [$ key] लिखा होगा या ऐसा कुछ ..)। – Alberto

संबंधित मुद्दे