1

我正在开发一个使用 Web 服务调用的应用程序。

我正在调用我的登录网络服务,如下所示

String url = "http://mydomaim.com/login.php";

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(userEmail, password, url);

它工作正常并向我发送响应,如下所示

{
 "userName":"a",
   "login_success":1,
   "user_id":"3",
   "session_id":"1067749aae85b0e6c5c5e697b61cd89d",
   "email":"a"
}

我解析了这个响应,并成功地在变量中获取了会话 ID。现在我必须调用一个附加这个 session_id 作为 cookie 值的其他 web 服务。

问题

如何将session_id我的 cookie 值存储在我的 Android 设备中并调用其他 Web 服务?

4

2 回答 2

2

试试这个,登录时调用这个请求。

DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);

        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
            System.out.println("Cookie: " + cookie.toString());

            if (cookie.getName().contains("PHPSESSID"))
                guid = cookie.getValue();

        }

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
于 2013-09-11T15:02:16.200 回答
1

你可以尝试这样的事情:

public static void myMethod(Map<String, String> cookies) throws IOException, PortalException {

        HttpParams httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams, 60000);

        HttpConnectionParams.setSoTimeout(httpParams, 240000);

        try {

            DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);

            if (cookies != null) {

                for (Map.Entry<String, String> entry : cookies.entrySet()) {

                    BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue());

                    cookie.setPath("/");
                    cookie.setDomain(new URL(url).getHost());

                    httpClient.getCookieStore().addCookie(cookie);
                }
            }

            HttpRequestBase request = null;

            if (post) {

                request = post(url, params, headers);

            } else {

                request = get(url, params, headers);

            }

            BasicHttpContext context = new BasicHttpContext();

            HttpResponse response = httpClient.execute(request, context);

                    //... etc

这个对我有用。

于 2013-06-05T16:32:49.767 回答