android - post 请求后获取 cookie

标签 android http post cookies

我正在尝试登录网站并存储 cookie,以便对进一步的请求进行身份验证。

我成功登录该站点并获得响应,但我无法正确存储 cookie。这是我用来登录的代码:

private String makePostRequest(String url, List<String> header_fields, List<String> header_values) {

    String sessionCookie = "";

    HttpResponse response = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);

    //Post Data
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(header_fields.size());

    for(int i = 0; i < header_fields.size(); i++){

        nameValuePair.add(new BasicNameValuePair(header_fields.get(i), header_values.get(i)));
    }
    //Encoding POST data
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    //making POST request.
    try {
        response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();
    InputStream is = null;
    StringBuilder stringBuilder = new StringBuilder();
    if (statusCode == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try {
                is = entity.getContent();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            int length;
            try {
                while ((length = is.read(buffer)) > 0) {
                    stringBuilder.append(new String(buffer, 0, length));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

     return stringBuilder.toString();
}

使用该代码我登录并获得响应字符串,我可以在其中看到我已成功登录。关于 cookie 的任何想法?无法让它工作。

更新

这是我用来获取 session cookie 的代码

HttpGet httpGet = new HttpGet(url);
Header[] header=response.getHeaders("Set-Cookie");
for(int i =0; i < header.length; i++) {
     httpGet.addHeader("Set-Cookie", (header[i].getValue()));
}

最佳答案

从 HTTP 响应中获取 cookie

Header[] mCookies = response.getHeaders("cookie");

在下一行之后

response = httpClient.execute(httpPost);

关于android - post 请求后获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29962127/

相关文章:

安卓目录大小

android - 单击抽屉导航项目,抽屉导航中的新 ListView

http - 缺少可观察方法 RxJS 5.0.0-beta.0

http - 如何通过http服务器强制刷新页面?

c# - ServiceStack:AppHost 不支持通过单例访问当前请求

post - 如何启用/禁用选择标签并使用 knockout 将其发布(即使禁用)

java - 正则表达式删除空格后的所有字符//Android Java

Android RecyclerView 在加载数据时滚动到顶部

javascript - jQuery ajax 没有将值发布到 php 脚本

html - 直接POST到URL不起作用?