关于Android连接request和response中携带cookie:
class LoginTask extends AsyncTask<String, Object, String> { @Override protected void onPreExecute() { progressDialog.setMessage("Loading..."); progressDialog.show(); } @Override protected String doInBackground(String... par) { HttpPost post = new HttpPost(par[0]); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("methodName", "login")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); /**add cookie * Cookie cookie=new BasicClientCookie("",""); * CookieSpecBase cookieSpecBase=new BrowserCompatSpec(); * List<Cookie> cookies=new ArrayList<Cookie>(); * cookies.add(cookie); * cookieSpecBase.formatCookies(cookies); * post.setHeader(cookieSpecBase.formatCookies(cookies).get(0)); */ DefaultHttpClient client=new DefaultHttpClient(); try { post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); try { res = client.execute(post); } catch (Exception e) { return "网络连接错误,请检查网络是否打开!"; } responseCode = res.getStatusLine().getStatusCode(); if (responseCode != 200) return "服务器正忙! 返回代码为:" + responseCode; /** get cookie * List<Cookie> cookiess=client.getCookieStore().getCookies(); * cookiess.get(0).getName(); * cookiess.get(0).getValue(); */ bis = new ByteArrayInputStream(EntityUtils.toByteArray(res .getEntity())); dis = new DataInputStream(bis); c = new Customers(); if (dis.readUTF().equals("notnull")) { c.setCustomerid(dis.readLong()); c.setUsername(dis.readUTF()); c.setPassword(dis.readUTF()); c.setRealname(dis.readUTF()); c.setIdentify(dis.readUTF()); c.setSex(dis.readUTF()); c.setBirthday(dis.readUTF()); c.setCustomeraddress(dis.readUTF()); c.setCreditcard(dis.readUTF()); c.setEmail(dis.readUTF()); c.setTelephone(dis.readUTF()); c.setAddress(dis.readUTF()); c.setZip(dis.readUTF()); c.setRemark(dis.readUTF()); wirteToFile(c.getUsername(), c.getPassword()); } else { return "请重新输入密码或者用户名不正确!"; } } catch (UnsupportedEncodingException e) { return "错误:UnsupportedEncodingException"; } catch (IOException e) { e.printStackTrace(); return "错误:读取流出错!"; } finally { try { if (dis != null || bis != null) { dis.close(); bis.close(); } } catch (IOException e) { return "关闭流失败"; } } return null; } @Override protected void onPostExecute(String result) { progressDialog.cancel(); if (result != null) { fail = true; alertDialog(result); } } }关于Android连接request和response中携带cookie
内容版权声明:除非注明,否则皆为本站原创文章。