2011-01-10 1 views
8

thực sự tôi mới trong Android và bây giờ tôi phải thêm cookie trong dự án của mình. tôi đang sử dụng HttpsUrlConnection. đây là cách tôi đang yêu cầu và nhận được phản hồi từ một máy chủ web và bây giờ tôi phải thêm cookie là tốt.cách sử dụng cookie trong HttpsURLConnection trong android

URL url = new URL(strUrl); 

HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 

connection.setRequestMethod("POST");  

connection.setRequestProperty("Content-Type", 
    "application/soap+xml; charset=utf-8"); 

    connection.setRequestProperty("Content-Length", ""+ 
      Integer.toString(request.getBytes().length)); 

    connection.setUseCaches (false); 
    connection.setDoInput(true); 
    connection.setDoOutput(true); 


    // send Request... 
    DataOutputStream wr = new DataOutputStream (connection.getOutputStream()); 
wr.writeBytes (request); 
wr.flush(); 
wr.close(); 

//Get response... 
DataInputStream is = new DataInputStream(connection.getInputStream());  
String line; 
StringBuffer response = new StringBuffer(); 
while((line = is.readLine()) != null) { 
    response.append(line); 
    } 
is.close(); 
FileLogger.writeFile("Soap.txt", "RESPONSE: " + methodName + "\n" + response); 
HashMap<String, String> parameters = null; 
try { 
    parameters = SoapRequest.responseParser(response.toString(), methodName); 
    } catch (ParserConfigurationException e) { 
    // TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (SAXException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
return parameters; 

bất kỳ trợ giúp sẽ được đánh giá cao, nhờ

Trả lời

14

Bạn có một hướng dẫn here (là cho URLConnection, nhưng HttpsURLConnection là một lớp con nên nó cũng nên làm việc).

Về cơ bản bạn phải làm:

connection.setRequestProperty("Cookie", myCookie); 

nơi myCookie có dạng "userId=igbrown" nếu chỉ có một hoặc "userId=igbrown; sessionId=SID77689211949; isAuthenticated=true" nếu nhiều (tách là dấu chấm phẩy VÀ khoảng trắng)