HTTPUrlConnection维护会话

时间:2017-12-28 13:11:09

标签: java session session-cookies

我在服务器上使用Restful Services并尝试在执行登录后维护相同的会话:

URL endpoint = new URL(getString(R.string.url_login));
// Create connection
HttpURLConnection myConnection = (HttpURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
// Create the data
String myData = "username=" + username + "&password=" + pwd;
// Enable data writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
rc = myConnection.getResponseCode();
if (rc == 200) {
        String  Cookie= myConnection.getHeaderField("Set-Cookie");
        URL endpoint2 = new URL(getString(R.string.url_checkUserType));
        HttpURLConnection myConnection2 = 
                 (HttpURLConnection)endpoint2.openConnection();
        myConnection2.setRequestMethod("GET");
        myConnection2.setRequestProperty("User-Agent", "my-rest-app-v0.1");
        myConnection2.setRequestProperty("Cookie", Cookie);
        rc2 = myConnection2.getResponseCode();
....
        }....

问题是rc2每次都是401,因为WebService无法识别requiest是同一会话的一部分。我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作

  1. 在服务器端,它检查传入的请求是否有" sessionId"在cookie中:如果没有,创建一个并将其作为响应返回;如果是,则它知道该请求属于已知会话
  2. 在客户端,成功登录后,检索" sessionId"来自响应,并将其设置在以下请求中
  3. ==

    connection.setRequestProperty("Cookie", "JSESSIONID=" + URLEncoder.encode(jSessionId, "UTF-8"));
    

答案 1 :(得分:0)

解决方案是使用适合我的Android Spring RESTful services