您现在的位置是:首页 > 文章详情

Okhttp3-基本用法

日期:2019-08-16点击:347

前言

Okhttp官网
Okhttp-Github

android网络框架之OKhttp一个处理网络请求的开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso)

用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)

官网的解释如下:

基本用法

1.集成
1.1.依赖
 implementation 'com.squareup.okhttp3:okhttp:3.11.0'

可以去Okhttp-Github 查看并依赖最新的版本。

1.2权限

添加网络权限

 <uses-permission android:name="android.permission.INTERNET" />
2.使用
2.1 同步GET请求
  • 构建OkHttpClient对象
  • 构建Request对象
  • 构建Call对象并通过execute()方法来执行同步Get请求
 //同步请求 OkHttpClient okHttpClient=new OkHttpClient(); final Request request=new Request.Builder() .url("https://www.wanandroid.com/navi/json") .get() .build(); final Call call = okHttpClient.newCall(request); try { Response response = call.execute(); Log.e("同步结果---- ",response.body().string()+""); } catch (IOException e) { e.printStackTrace(); }

运行后发现报错:

 android.os.NetworkOnMainThreadException

在Android4.0以后,会发现,只要是写在主线程(就是Activity)中的HTTP请求,运行时都会报错,这是因为Android在4.0以后为了防止应用的ANR(Aplication Not Response)异常。解决方法就是在子线程中运行:

 //同步请求 OkHttpClient okHttpClient=new OkHttpClient(); final Request request=new Request.Builder() .url("https://www.wanandroid.com/navi/json") .get() .build(); final Call call = okHttpClient.newCall(request); new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute(); Log.e("同步结果---- ",response.body().string()+""); } catch (IOException e) { e.printStackTrace(); } } }).start();
2.2 异步GET请求
 //异步请求 OkHttpClient okHttpClient=new OkHttpClient(); final Request request=new Request.Builder() .url("https://www.wanandroid.com/navi/json") .get() .build(); final Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("okhttp_error",e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Gson gson=new Gson(); Log.d("okhttp_success",response.body().string()); } });
2.3 POST请求

POST请求支持提交文件,流,string,表单等等 。这里拿POST表单请求作为请求示例:

 OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder() .add("username", "qinzishuai") .add("password", "111111") .build(); Request request = new Request.Builder() .url("https://www.wanandroid.com/user/login") .post(requestBody) .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d("okhttp", "onFailure: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d("okhttp", "onResponse: " + response.body().string()); } }); 

大家可以关注我的微信公众号:「秦子帅」一个有质量、有态度的公众号!

原文链接:https://yq.aliyun.com/articles/714777
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章