android 保持同一Session网络请求

来源:互联网 发布:企业备案域名购买 编辑:程序博客网 时间:2024/05/17 00:13

遇到过这种问题,手机注册获取验证码的时候,总是说验证码过期,明明刚获取的验证码,还是提示验证码过期。这种情况就是多次网络请求不在同一个Session,很可能就是用了不同的请求方法造成的(eg:httpUrlConnection和httpCilent的get请求或者post请求,建议这种情况就用同一种请求方法的post请求)

关于多次网络请求不在同一个Session(会话)的原因:每次请求的方法不同(例如:分别使用httpclient和httpUrlConnecttion等不同的网络请求方法)

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

简单封装post请求

public class HttpUtils {    // 创建HttpClient对象    public static HttpClient httpClient = new DefaultHttpClient();    //服务端返回的String    public static String str;    /*     * 封装post请求     */    public static String httpPost(final String url,            final List<NameValuePair> list_params) {                try {                    // 得到HttpPost对象                    HttpPost httpPost = new HttpPost(url);                    httpPost.setEntity(new UrlEncodedFormEntity(list_params,                            HTTP.UTF_8));                    // 客户端使用POST方式执行请求,获得服务器端的回应response                    HttpResponse respone = httpClient.execute(httpPost);                    // 判断是否请求成功                    if (respone.getStatusLine().getStatusCode() == 200) {                        // 获取输入流                        InputStream inStream = respone.getEntity().getContent();                        int len;                        byte b[] = new byte[1024];                        ByteArrayOutputStream bos = new ByteArrayOutputStream();                        while ((len = inStream.read(b)) != -1) {                            bos.write(b, 0, len);                        }                        str = bos.toString();                    }                } catch (UnsupportedEncodingException e) {                    e.printStackTrace();                } catch (ClientProtocolException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }        return str;    }}

在需要网络请求的地方调用

    new Thread() {            public void run() {            //请求参数                List<NameValuePair> list_params = new ArrayList<NameValuePair>();                list_params.add(new BasicNameValuePair("uname", "xiaomeng"));                list_params.add(new BasicNameValuePair("loginPassword",                        "123456"));                String response = HttpUtils.httpPost(url, list_params);                Log.i(TAG, response);            };        }.start();
0 0
原创粉丝点击