HTTPUrlConnection 维护会话

HTTPUrlConnection maintain session

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

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 是同一会话的一部分。我做错了什么?

您可以进行如下操作

  1. 在服务器端,它检查传入请求是否在 cookie 中包含 "sessionId":如果没有,则创建一个并 return 作为响应;如果是,它知道该请求属于已知会话
  2. 在客户端,登录成功后,从响应中获取"sessionId",并在后面的请求中设置

==

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

解决方案是对 Android 使用 Spring RESTful services,这对我来说非常有效。