關於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);
- }
- }
- }