大佬教程收集整理的这篇文章主要介绍了Android:使用DefaultHttpClient登录网站并保留会话/ Cookie,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我要做的:我想登录一个需要用户身份验证的网站,然后阅读并解析仅当用户登录时才能访问的网站.
问题:在将凭据发送到网站后,我收到一个似乎不保存在我的httpClient中的cookie,尽管文档建议应该会发生.
这是我的一些代码:
DefaulthttpClient httpclient = new DefaulthttpClient(); httpPost httpost = new httpPost(LOGIN_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(user_FIELD,login)); nvps.add(new BasicNameValuePair(PASS_FIELD,pw)); nvps.add(new BasicNameValuePair(REMEMBERME,"on")); httpost.setEntity(new UrlEncodedFormEntity(nvps,http.UTF_8)); httpResponse response = httpclient.execute(httpost); httpentity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } List<Cookie> cookies = httpclient.getCookieStore().getCookies();
当我输出“cookies”的内容时,一切似乎都很好(我收到一个会话):
– [version:0] [name:ASP.NET_SessionId] [value:xxx] [domain:xxx] [path:/] [expiry:null]
据我所知,只要我没有关闭它,Cookie /会话将被保留并在我的httpClient中使用.
httpGet httpget2 = new httpGet(REStriCTED_URL); response = httpclient.execute(httpget2); entity = response.getEntity(); InputStream data = entity.getContent(); // data will be parsed here if (entity != null) { entity.consumeContent(); } // connection will be closed afterWARDs
如果我输出GET请求的响应(使用response.getStatusLine()),我得到一个“200 OK”消息,但解析返回的站点显示登录丢失(我只检索登录表单).
任何帮助是赞赏.
以下代码是用于在JBoss中运行的应用程序
public Boolean login() { httpGet httpGet = new httpGet( "http://localhost:8080/gwt-console-server/rs/identity/secure/sid/"); httpPost httpPost = new httpPost("http://localhost:8080/gwt-console-server/rs/identity/secure/j_security_check"); httpResponse response = null; List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(user_FIELD,userName)); nvps.add(new BasicNameValuePair(PASS_FIELD,password)); try { httpPost.setEntity(new UrlEncodedFormEntity(nvps,http.UTF_8)); response = httpClient.execute(httpGet); EntityUtils.consume(response.getEntity()); response = httpClient.execute(httpPost); EntityUtils.consume(response.getEntity()); response = httpClient.execute(httpGet); String sessionId =EntityUtils.toString(response.getEntity()); String cookiEID =""; List<Cookie> cookies = ((AbstracthttpClient) httpClient).getCookieStore().getCookies(); for (Cookie cookie: cookies){ if (cookie.getName().equals("JSESSIONID")){ cookiEID = cookie.getValue(); } } if(sessionId!= null && sessionId.equals(cookiEID) ){ return true; } } catch (ClientProtocolException E) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException E) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
以上是大佬教程为你收集整理的Android:使用DefaultHttpClient登录网站并保留会话/ Cookie全部内容,希望文章能够帮你解决Android:使用DefaultHttpClient登录网站并保留会话/ Cookie所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。