OKHttp使用总结

来源:互联网 发布:网络技术交流论坛 编辑:程序博客网 时间:2024/05/21 06:40

OkHttp,链接:http://square.github.io/okhttp/

1、OkHttp,Square的一款产品,是一个Java的开源HTTP和SPDY客户端开发包,支持Android。

2、 Square,那些热衷于Android 开源或分享的国外开发者及公司,一度被视为 Android 开源界最良心的企业!
GitHub: https://github.com/square
博客: http://square.github.io/
代表作:
okhttp, fest-android(测试),
android-times-square(timepicker),
picasso(图片下载缓存库)
dagger(依赖注入框架)
spoon(兼容性测试工具)

3、// 使用HttpURLConnection 连接,个人比较常用

protected void urlConn() {           try {                 URL url = new URL(XXXURL);                  HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();              if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {                   Toast(连接Google Weather API成功!)                InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");                   int i;                   String content = "";                   while ((i = isr.read()) != -1) {                          content = content + (char) i;                   }                   isr.close();                   tv.setText(content);   //设置TextView,这个就有问题,应该开启一下线程,然后接着用handle处理message            }               httpconn.disconnect();  //disconnect           } catch (Exception e) {               Toast("连接Google Weather API失败")            e.printStackTrace();           }       }   

4、使用 HttpCient连接

protected void httpClientConn() {           DefaultHttpClient httpclient = new DefaultHttpClient();           HttpGet httpget = new HttpGet(XXXURL);             ResponseHandler<STRING> responseHandler = new BasicResponseHandler();             try {               String content = httpclient.execute(httpget, responseHandler);               Toast("连接Google Weather API成功!") ;            tv.setText(content);           } catch (Exception e) {               Toast( "连接Google Weather API失败");            e.printStackTrace();           }           httpclient.getConnectionManager().shutdown();       }   }

5、回顾一下,//记得开线程,tv记得用handlemessage来处理,权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

6、Android自带的两个HTTP框架(HttpURLConnection和HttpClient),在各种Android OS版本一直充斥着错误,可以使任何理智的开发者走向崩溃。不过幸运地是,OkHttp解决了这些问题。
OkHttp是建立在HttpUrlConnection上,从Android4.4开始HttpURLConnection的底层实现采用的是okHttp.从Android代码库保持最新的修复,这意味着再也没有与旧操作系统版本出现兼容性问题的噩梦。

7、OKHttp是Android版Http客户端。An HTTP & SPDY client for Android and Java applications
非常高效,支持SPDY、连接池、GZIP和 HTTP 缓存。
默认情况下,OKHttp会自动处理常见的网络问题,像二次连接、SSL的握手问题。
如果你的应用程序中集成了OKHttp,Retrofit默认会使用OKHttp处理其他网络层请求。这里有个Retrofit我下次会讲一下。

8、
使用要求:
对于Android: 2.3以上
对于Java: Java7以上

两个模块:
okhttp-urlconnection实现.HttpURLConnection API;
okhttp-apache实现Apache HttpClient API.

依赖:
okio(https://github.com/square/okio):
Okio, which OkHttp uses for fast I/O and resizable buffers.

安装:
在AS 中使用:
Maven:com.squareup.okhttpokhttp2.3.0
Gradle:compile ‘com.squareup.okhttp:okhttp:2.3.0’

在Eclipse中使用:
导入两个jar包:okhttp,okio的jar包

9、HTTP是应用层的网络传输协议
对于HTTP的请求方式主要流行的GET请求与POST请求对于GET请求与POST请求的区别

  • 请求方式与请求参数不同

GET请求,服务器以及参数都会出现在请求接口中,请求参数是接口一部分
POST请求,在接口中只有服务器地址,而参数会作为请求,提交给服务器。

  • 安全性问题

GET请求会出现在请求接口中,所以信息容易被捕获,安全性低
POST请求参数封装在请求体中,作为二进制流进行传输,不易被捕获,安全性高。

  • 字数限制,适用场景

GET在请求时,接口的字节数有限制,支持小数据的提交,
POST请求,从理论上来讲没有限制性
虽然理论上对于GET请求与POST请求都可以提交请求,但是GET多用于从服务器请求数据,而POST多用于向服务器提交数据。

10、同步和异步的区别

  • 使用同步连接,请求数据
    当数据还未请求成功之前,用户界面做任何操作都是无效的,都是不会响应的。
    只有当请求数据完毕之后,才会响应用户交互,通常会卡死主线程
  • 使用异步连接,请求数据
    有单独的子线程去请求数据,而主线程依然响应处理用户交互,此时用户交互得到处理,用户流畅操作,用户体验比较好,所以开发过程中最多的还是异步连接。

11、get请求的书写

    public void get(){          BufferedReader in = null;          try{              HttpClient client = new DefaultHttpClient();              HttpGet request = new HttpGet();              request.setURI("www.baidu.com");              HttpResponse response = client.execute(request);               in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));                 StringBuffer sb = new StringBuffer("");               String line = "";              String NL = System.getProperty("line.separator");              while((line = in.readLine()) != null){                  sb.append(line + NL);             }              in.close();              String page = sb.toString();              Log.i(TAG, page);          }catch(Exception e){              Log.e(TAG,e.toString())          }finally{              if(in != null){                  try{                      in.close();                  }catch(IOException ioe){                      Log.e(TAG, ioe.toString());                  }              }          }      }

带参数的 HTTP GET:

HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");  client.execute(request);  

12、Post请求的书写

 public void post(){          BufferedReader in = null;          try{              HttpClient client = new DefaultHttpClient();              HttpPost request = new HttpPost("http://localhost/upload.jsp");               List<NameValuePair> postParams = new ArrayList<NameValuePair>();              postParams.add(new BasicNameValuePair("filename", "sex.mov"));              UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);              request.setEntity(formEntity);              HttpResponse response = client.execute(request);              in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));                 StringBuffer sb = new StringBuffer("");               String line = "";              String NL = System.getProperty("line.separator");              while((line = in.readLine()) != null){                  sb.append(line + NL);              }              in.close();              String result = sb.toString();          }catch(Exception e){              Log.e(TAG,e.toString())          }finally{              if(in != null){                  try{                      in.close();                  }catch(IOException ioe){                      Log.e(TAG, ioe.toString());                  }              }          }      } 
0 0
原创粉丝点击