【问题标题】:how to use cookies in HttpsURLConnection in android如何在 android 的 HttpURLConnection 中使用 cookie
【发布时间】:2011-01-10 14:55:10
【问题描述】:

实际上我是 Android 新手,现在我必须在我的项目中添加 cookie。我正在使用 HttpsUrlConnection。这是我如何从网络服务器发出请求并获得响应,现在我还必须添加 cookie。

   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;

任何帮助将不胜感激,谢谢

【问题讨论】:

    标签: android cookies https


    【解决方案1】:

    您有一个教程here(适用于URLConnection,但HttpsURLConnection 是一个子类,所以它也应该可以工作)。

    基本上你必须这样做:

    connection.setRequestProperty("Cookie", myCookie);
    

    其中myCookie 的形式为"userId=igbrown"(如果只有一个)或"userId=igbrown; sessionId=SID77689211949; isAuthenticated=true"(如果有多个)(分隔符是分号和空格)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2018-06-01
      • 2015-01-01
      • 2013-04-15
      • 1970-01-01
      • 2019-09-26
      • 2012-09-03
      相关资源
      最近更新 更多