android 开发中接触的各种网络请求框架总结
来源:互联网 发布:培育发展新动力 优化 编辑:程序博客网 时间:2024/05/09 15:55
前言:
开发中接触了不少网络请求的框架,包括Volley,HttpCliet AsyncHttpClient,Okhttp,OkhttpUtils,HttpUrlConnection,Retrofit。虽说一个项目顶多使用一种框架,但是我们难免接触基于不同框架下开发的app,所以认识和了解它们就显得很有必要,而且,我很确定在你手中项目的基础上你可以很熟练的使用项目依赖的框架进行网络的访问请求,但是抛开你的项目,我感觉你会和我一样变得像一个只记得他们大概的使用情形,但是具体写每一行的代码,会让你无从下手,所以在此总结各种网络请求框架的使用方法就很有必要啦。
1、HttpClient
在Android开发中,Android SDK附带了Apache的HttpClient,它是一个完善的客户端。它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执行HTTP 的GET和HTTP POST调用。HttpClient上午API比较多,同时也比较稳定但是他不利于对他进行升级,在安卓5.0时废除了此方法,6.0是直接删除.
使用步骤:
1.使用DefaultHttpClient类实例化HttpClient对象
2.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
3.调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
4.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
GET请求:
BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("http://code.google.com/android/"); //使用NameValuePair来保存要传递的Post参数 List<namevaluepair> postParameters = new ArrayList<namevaluepair>(); //添加要传递的参数 postParameters.add(new BasicNameValuePair("id", "12345")); postParameters.add(new BasicNameValuePair("username", "dave")); //实例化UrlEncodedFormEntity对象 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( postParameters); //使用HttpPost对象来设置UrlEncodedFormEntity的Entity request.setEntity(formEntity); HttpResponse response = client.execute(request); in = new BufferedReader( new InputStreamReader( response.getEntity().getContent())); StringBuffer string = new StringBuffer(""); String lineStr = ""; while ((lineStr = in.readLine()) != null) { string.append(lineStr + "\n"); } in.close(); String resultStr = string.toString(); System.out.println(resultStr); } catch(Exception e) { // Do something about exceptions } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }
POST请求:
try
{
//得到HttpClient对象 HttpClient getClient = new DefaultHttpClient(); //得到HttpGet对象 HttpGet request = new HttpGet(uri); //客户端使用GET方式执行请教,获得服务器端的回应response HttpResponse response = getClient.execute(request); //判断请求是否成功 if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ Log.i(TAG_STRING, "请求服务器端成功"); //获得输入流 InputStream inStrem = response.getEntity().getContent(); int result = inStrem.read(); while (result != -1){ System.out.print((char)result); result = inStrem.read(); } //关闭输入流 inStrem.close(); }else { Log.i(TAG_STRING, "请求服务器端失败"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
HTTPURLConnection:多用途轻量级的HTTP客户端,适用于大多数应用程序,API较少,便于进行升级扩展,在4.0版本之后添加了相应的缓存机制