[android]-如何在向服务器发送request时附加已保存的cookie数据

[android]-如何在向服务器发送request时附加已保存的cookie数据

应用场景:
在开发android基于手机端+服务器端的应用时,登陆->获取用户信息->获取授权用户相关业务数据(如用户工作任务安排)
,此时就涉及到在登陆后必须把保存有用户已登陆的cookie数据(和服务器端使用cookie或session来判断用户是否登陆没关系,因为这两种方式,在客户端来说,都是通过保存cookie数据来实现的)一同发送到服务器端,不然,服务器端会认为你没有登陆,而不给提供用户工作任务安排的数据

我在工作中就遇到过这问题

一开始我是这样书写代码的

01 import java.io.IOException;
02 import java.net.SocketTimeoutException;
03 import java.util.ArrayList;
04 import java.util.List;
05 import org.apache.http.HttpResponse;
06 import org.apache.http.NameValuePair;
07 import org.apache.http.client.methods.HttpPost;
08 import org.apache.http.impl.client.AbstractHttpClient;
09 import org.apache.http.impl.client.DefaultHttpClient;
10  
11  
12 String result = "";
13 /* HTTP Post */
14 HttpPost httpRequest = new HttpPost(url);
15  
16 List<NameValuePair> params = new ArrayList<NameValuePair>();
17 params.add(new BasicNameValuePair(para, data));// jsonParameter
18  
19 try {
20     // HTTP request
21     httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
22     // HTTP response
23  
24     DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
25     // 请求超时
26     defaultHttpClient.getParams().setParameter(
27             CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
28     // 读取超时
29     defaultHttpClient.getParams().setParameter(
30             CoreConnectionPNames.SO_TIMEOUT, 10000);
31              
32  
33     // 发送请求
34     HttpResponse httpResponse = defaultHttpClient.execute(httpRequest);
35  
36     // 得到应答的字符串
37     // 200 ok
38     if (httpResponse.getStatusLine().getStatusCode() == 200) {
39         result = EntityUtils.toString(httpResponse.getEntity());
40          
41     }
42 catch (ClientProtocolException e) {
43     System.out.println("ClientProtocolException:" + e.toString());
44     e.printStackTrace();
45     return null;
46 catch (UnsupportedEncodingException e) {
47     System.out.println("UnsupportedEncodingException:" + e.toString());
48     e.printStackTrace();
49 catch (SocketTimeoutException e) {
50     System.out.println("SocketTimeoutException:" + e.toString());
51     e.printStackTrace();
52 catch (IOException e) {
53     System.out.println("IOException:" + e.toString());
54     e.printStackTrace();
55 }

调用发现登陆成功后在获取工作任务时服务器提示未登陆,看来是没把cookie发送到服务器,由是找资料

修改后如下,有两个类
WebHelperResponse.java

1 package com.demo.utils;
2  
3 public class WebHelperResponse {
4     public String ResponseText = "";
5     public boolean IsOk = false;
6     public boolean IsError = false;
7     public String ErrMsg = "";
8 }

WebHelper.java

001 package com.nt.android.app.slorders.utils;
002  
003 import java.io.IOException;
004 import java.net.SocketTimeoutException;
005 import java.util.ArrayList;
006 import java.util.List;
007 import org.apache.http.HttpResponse;
008 import org.apache.http.NameValuePair;
009 import org.apache.http.client.CookieStore;
010 import org.apache.http.client.entity.UrlEncodedFormEntity;
011 import org.apache.http.client.methods.HttpPost;
012 import org.apache.http.impl.client.AbstractHttpClient;
013 import org.apache.http.impl.client.DefaultHttpClient;
014 import org.apache.http.message.BasicNameValuePair;
015 import org.apache.http.params.CoreConnectionPNames;
016 import org.apache.http.protocol.HTTP;
017 import org.apache.http.util.EntityUtils;
018  
019 public class WebHelper {
020  
021     private static CookieStore cookieStore;
022  
023     public static WebHelperResponse postJson(String url, String data) {
024         return postData(url, data, "jsondata");
025     }
026  
027     public static WebHelperResponse postXml(String url, String data) {
028         return postData(url, data, "xmldata");
029     }
030  
031     // url参数中不允许有空格,否则将在new HttpPost(url)引发java.lang.IllegalArgumentException错误
032     public static WebHelperResponse postData(String url, String data,
033             String para) {
034         WebHelperResponse m_response = new WebHelperResponse();
035         m_response.IsOk = false;
036         m_response.IsError = false;
037  
038         String result = "";
039         /* HTTP Post */
040         HttpPost httpRequest = new HttpPost(url);
041         // param NameValuePair[]
042         // request.getParameter("name")
043         List<NameValuePair> params = new ArrayList<NameValuePair>();
044         params.add(new BasicNameValuePair(para, data));// jsonParameter
045  
046         try {
047             // HTTP request
048             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
049             // HTTP response
050  
051             DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
052             // 请求超时
053             defaultHttpClient.getParams().setParameter(
054                     CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
055             // 读取超时
056             defaultHttpClient.getParams().setParameter(
057                     CoreConnectionPNames.SO_TIMEOUT, 10000);
058             // 添加Cookie
059             if (cookieStore != null) {
060                 defaultHttpClient.setCookieStore(cookieStore);
061             }
062  
063             // 发送请求
064             HttpResponse httpResponse = defaultHttpClient.execute(httpRequest);
065             int responseStatusCode = httpResponse.getStatusLine()
066                     .getStatusCode();
067             System.out.println("response statuscode:" + responseStatusCode);
068             // 得到应答的字符串
069             // 200 ok
070             if (responseStatusCode == 200) {
071                 result = EntityUtils.toString(httpResponse.getEntity());
072                 // 保存Cookie
073                 cookieStore = ((AbstractHttpClient) defaultHttpClient)
074                         .getCookieStore();
075  
076                 m_response.IsError = false;
077                 m_response.IsOk = true;
078                 m_response.ResponseText = result;
079  
080             else if (responseStatusCode == 404) {
081                 // 找不到页面
082                 m_response.IsError = true;
083                 m_response.IsOk = false;
084                 System.out.println("404:page not found.");
085                 m_response.ErrMsg = "不存在此服务,请检查服务器地址配置";
086             else {
087                 m_response.IsError = true;
088                 m_response.IsOk = false;
089                 System.out.println("error,responsestatuscode:"
090                         + responseStatusCode);
091                 m_response.ErrMsg = "服务出错";
092             }
093         catch (SocketTimeoutException e) {
094             System.out.println("ClientProtocolException:" + e.toString());
095             e.printStackTrace();
096  
097             m_response.IsError = true;
098             m_response.IsOk = false;
099             m_response.ErrMsg = "连接错误:未能连接到服务器!";
100  
101         catch (IOException e) {
102             System.out.println("ClientProtocolException:" + e.toString());
103             e.printStackTrace();
104  
105             m_response.IsError = true;
106             m_response.IsOk = false;
107             m_response.ErrMsg = "错误:服务器未能提供服务!";
108  
109         }
110         return m_response;
111     }
112  
113 }
上一篇:LeetCode Day1


下一篇:python爬虫(七)_urllib2:urlerror和httperror