十五.Android网络通信与Volley简单介绍

来源:互联网 发布:nginx grpc 编辑:程序博客网 时间:2024/05/02 00:55

1.Android 网络通信

  • URL请求的类别
    GET:参数放在url里。
    POST:参数放在http请求报文中。

1.1 HttpURLConnection

  • 创建Url
URL url = new URL("http://www.baidu.com");
  • 创建HttpURLConnection,引用为url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
  • 设置请求方式GET或POST
connection.setRequestMethod("GET");connection.setRequestMethod("POST");
  • 设置连接超时和读取超时
connection.setConnectTimeout("8000");connection.setReadTimeout("8000");
  • 读取返回的内容
InputStream in = connection.getInputStream();BufferedReader reader=new BufferedReader(new InputStreamReader(in));StringBuilder response=new StringBuilder();while((line=reader.readLine())!=null){    response.append(line);}
  • 断开连接
connection.disconnect();

1.2 HttpClient

  • 创建HttpClient并引用DefaultHttpClient()。
HttpClient httpClient=new DefaultHttpClient();
  • 设置请求方式GET或POST
//get方法HttpGet httpGet =new HttpGet("http://www.baidu.com");httpClient.execute(httpGet);//post方法HttpPost httpPost=new HttpPost("http://www.baidu.com");List<NameValuesPair> params =new ArrayList<NameValuesPair>();params.add(new BasicNameValuePair("username","admin"));params.add(new BasicNameValuePair("password","123456"));UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");httpPost.setEntity(entity);httpClient.excute(httpPost);
  • 判定返回为200,并获取返回参数
if(httpRespnse.getStutusLine().getSttusCode()==200){  HttpEntity entity=httpResponse.getEntity();  String response=EntityUtils.toString(entity,"utf-9");}

1.3 比较

  • 在 Froyo(2.2) 之前,HttpURLConnection 有个重大 Bug,调用 close() 函数会影响连接池,导致连接复用失效,所以在 Froyo 之前使用 HttpURLConnection 需要关闭 keepAlive。 另外在 Gingerbread(2.3) HttpURLConnection 默认开启了 gzip 压缩,提高了 HTTPS 的性能,Ice Cream Sandwich(4.0) HttpURLConnection 支持了请求结果缓存。 再加上 HttpURLConnection 本身 API 相对简单,所以对 Android 来说,在 2.3 之后建议使用 HttpURLConnection,之前建议使用 AndroidHttpClient。

2.Volley框架

2.1 概述

  • Google官方在2013年Google I/O大会上推出了一个新的网络通信框架——Volley。使得Android应用网络操作更方便更快捷;抽象了底层Http Client等实现的细节,让开发者更专注与产生RESTful Request。另外,Volley在不同的线程上异步执行所有请求而避免了阻塞主线程。
    这个框架可是Google给亲儿子Android的福利啊。

2.2 用法

  • Android Studio使用Volley
    1. 下载Volley,需要翻墙~

      git clone https://android.googlesource.com/platform/frameworks/volley
    2. Android studio File–New–new module,添加即可。
  • 创建一个RequestQueue对象。
RequestQueue mQueue = Volley.newRequestQueue(context);  
  • 创建一个StringRequest对象。
//GET方法StringRequest stringRequest = new StringRequest("http://www.baidu.com",                          new Response.Listener<String>() {                              @Override                              public void onResponse(String response) {                                  Log.d("TAG", response);                              }                          }, new Response.ErrorListener() {                              @Override                              public void onErrorResponse(VolleyError error) {                                  Log.e("TAG", error.getMessage(), error);                              }                          });  //POST方法StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {      @Override      protected Map<String, String> getParams() throws AuthFailureError {          Map<String, String> map = new HashMap<String, String>();          map.put("params1", "value1");          map.put("params2", "value2");          return map;      }  };  
  • 将StringRequest对象添加到RequestQueue里面。
mQueue.add(stringRequest);  
  • 这样几个步骤就很方便的进行了网络通信。
0 0
原创粉丝点击