在项目中很多情况需要对现有的web网页进行解析和表单提交模拟,最近做毕业设计的时候用到了Android平台提交登陆表单并且要带上Cookie。研究一番后如下:
/** * 登陆到主页面 */ private void login() { HttpPost post = new HttpPost( "http://sso.hhit.edu.cn/default.aspx?ReturnUrl=http://sso.hhit.edu.cn:80/Logout.aspx"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(API.HIDINE1_NAME, API.HIDINE1_VALUE)); params.add(new BasicNameValuePair(API.HIDINE2_NAME, API.HIDINE2_VALUE)); params.add(new BasicNameValuePair(API.LOGIN_NAME, mEditTextId.getText() .toString().trim())); params.add(new BasicNameValuePair(API.LOGIN_PWD, mEditTextPassword .getText().toString().trim())); params.add(new BasicNameValuePair(API.LOGIN_VCODE, mEditTextValidation .getText().toString().trim())); params.add(new BasicNameValuePair(API.LOGIN_BUTTON1, "")); // 加入cookie AppContext.showLog("cookieName:" + mCookieName + "cookieValue:" + mCookieValue); Cookie cookie = new BasicClientCookie(mCookieName, mCookieValue); post.setHeader("Cookie", "" + mCookieName + "=" + mCookieValue + ";"); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse res = null; HttpEntity entity = null; try { post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); res = client.execute(post); entity = res.getEntity(); AppContext.showLog("返回内容" + EntityUtils.toString(entity)); } catch (Exception e) { e.printStackTrace(); } int responseCode = res.getStatusLine().getStatusCode(); AppContext.showLog("服务器正忙! 返回代码为:" + responseCode); if (responseCode != 200) AppContext.showLog("服务器正忙! 返回代码为:" + responseCode); // 得到cookie List<Cookie> cookiess = client.getCookieStore().getCookies(); for (Cookie cookie2 : cookiess) { AppContext.showLog("返cookie为:" + cookie2.getName() + "--" + cookie2.getValue()); } }
中一个回答一样
to add cokie use it like this: it should be added in header
post.addHeader("Cookie", " PHPSESSID="+PHPSESSID+"; gc_userid="+gc_user+"; gc_session="+gc);
for you it should be like:
httpost.addHeader("Cookie","session_id = 1234;"...)