【问题标题】:HTTPUrlConnection maintain sessionHTTPUrlConnection 维护会话
【发布时间】:2018-06-09 00:58:01
【问题描述】:

我在服务器上使用 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 是同一会话的一部分。我做错了什么?

【问题讨论】:

标签: java session session-cookies


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你可以这样做

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

    ==

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

    【讨论】:

    • 为什么需要对 jSessionId 进行编码?变量Cookie 包含类似JSESSIONID=FA4D1226F11D2EBCB85361D5D9CA703F; Path=/My_Server; HttpOnly 的字符串,看来您是否在做同样的事情?
    • 就是把一个字符串翻译成application/x-www-form-urlencoded格式,URL中不允许有任何字符。
    • 但是如果它是由服务器返回的,它应该被允许吗?任何方式 Spring Security(*我在服务器端使用的)仍然拒绝它
    • jSessionId 的编码不是必需的,具体取决于 id 的生成方式。如果你使用的是 Spring Security,并且没有配置为stateless,那么会话 id 已经存在,你只需要在发送下一个请求时设置它。如果这不起作用,您会在服务器日志中看到什么错误?
    • 授权部分失败:http.authorizeRequests() .antMatchers("/restapii/*").authenticated() 这就是我得到unauthorized 的原因。如果我更改.permitAll(),它会起作用(显然)。我确信服务器端没有错误,因为它可以在浏览器中完美运行,并且此代码适用于 MobileApp
    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2013-02-04
    • 2013-11-18
    相关资源
    最近更新 更多