如何在Java中存储cookie Android?

时间:2015-05-22 14:30:56

标签: java android cookies

我想使用我在Java应用程序中使用的同一个类,它在PHP服务器上使用Cookie机制。实际的类在Java中运行得很好:

public class Connection {

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 个答案:

答案 0 :(得分:1)

据我所知,想法是存储从服务器收到的令牌。您可以使用以下代码将令牌保存到共享首选项,无论何时需要再次提出请求,请阅读令牌并使用它签署您的请求。

将令牌写入共享首选项:

List<Double> listA = getListA();
List<Double> listB = getListB();
List<Double> listC = getListC();

int listsSize = listA.size();

    List<?> collect = IntStream.range(0, listsSize)
            .mapToObj(i -> listA.get(i) + listB.get(i) + list(C).get(i))
            .collect(toList());

阅读令牌:

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

editor.putString(ACCESS_TOKEN_STRING, token);

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