2015-05-22 40 views
0

我想要使用与Java应用程序中使用的相同的类,该应用程序通过PHP服务器使用Cookie机制。实际的类,在Java的伟大工程:如何在Java中存储Cookie Android?

公共类连接{

private HttpURLConnection connection; 
private String username; 
private String password; 

public Connection(String username, String password) { 
    super(); 
    this.username = username; 
    this.password = password; 
    CookieHandler.setDefault(new CookieManager()); 
    login(); 
} 

public Connection() { 
    CookieHandler.setDefault(new CookieManager()); 
} 

public void setCredentials(String username, String password) { 
    this.username = username; 
    this.password = password; 
    login(); 

} 

public String login() { 
    String urlParameters = "username=" + username + "&password=" + password 
      + "&ac=log"; 
    return sendPost(
      my url.php", 
      urlParameters); 

} 

public String sendPost(String destination, String post) { 
    try { 
     URL url = new URL(destination); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(
       connection.getOutputStream()); 

     wr.writeBytes(post); 
     wr.flush(); 
     wr.close(); 

     InputStream is = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
     } 
     rd.close(); 
     return response.toString(); 

    } catch (Exception e) { 

     return null; 

    } finally { 

     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

}

下的Java,我能够管理从服务器接收cookie的,没有任何问题;在Android中,当我执行方法login()时,我获得了一个新的PHPsession;那么如何解决这个问题呢?我只想保持与Android和PHP服务器之间的认证连接。

回答

1

所以,据我所知,这个想法是存储你从服务器收到的令牌。您可以使用下面的代码将令牌保存为共享首选项,并且每当您需要再次发出请求时,请阅读令牌并使用该令牌签名。

写令牌到共享偏好:

SharedPreferences settings = context.getSharedPreferences(SHARED_PREFERENCES_NAME, 0); 
SharedPreferences.Editor editor = settings.edit(); 

editor.putString(ACCESS_TOKEN_STRING, token); 

/* Commit the edits */ 
editor.commit(); 

来读取令牌:

SharedPreferences settings = context.getSharedPreferences(SHARED_PREFERENCES_NAME, 0); 
return settings.getString(ACCESS_TOKEN_STRING, ""); 
+0

这就是我认为的解决方案,但我希望在Java代码将工作,只要使用相同的码。 –

+0

我之前没有使用CookiHandler或CookieManager,不知道它是如何工作的。但它似乎在Android包中,所以它应该在Java中工作。 – osayilgan