2

Android入门第55天-在Android里使用OKHttp组件访问网络资源

 1 year ago
source link: https://blog.csdn.net/lifetragedy/article/details/128424733
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

今天的课程开始进入高级课程类了,我们要开始接触网络协议、设备等领域编程了。在今天的课程里我们会使用OKHttp组件来访问网络资源而不是使用Android自带的URLConnection。一个是OKHttp组件更方便二个是OKHttp组件本身就带有异步回调功能。

下面就进入课程。

e8e3b6fc40bf43158227377d14484fe2.png
f564ead0f8ea48e9a9e06f0c3f419e54.png
cb523c6081bc4c16a299101c71a7acef.png

我们的课程目标有4个点:

  1. 使用OKHttp组件;
  2. 使用OKHttp组件加载网络图片显示在APP的ImgView里;
  3. 使用OKHttp组件加载给定网页代码显示在ScrollView里;
  4. 使用OKHttp组件加载给定网页显示在WebView里;

以上过程都为异步加载。

代码前在gradle里要先声明对于OKHttp组件的引用

要使用OKHttp组件,我们必须要在build.gradle中加入以下语句:

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

 以下是加完上述语句后的build.gradle。

647dba2a7284446baadf0f23b9864a5f.png

 访问网络资源需要给到APP以权限

我们因为要访问网络资源,因此我们需要给到APP以相应的权限。编辑AndroidManifest.xml文件,并加入以下两行声明。

 加完后的AndroidManifest.xml长这样

2475facae4a2401495995afa421e5279.png

菜单res\menu\pop_menu.xml

主UI界面



newCodeMoreWhite.png

MainActivity

String imgPath = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi2%2F2542318073%2FO1CN01fJvTi029VTwR16EvP_%21%212542318073.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673938156&t=69e5ee87fbf4b81b5f6eea53ed5b5158";
newCodeMoreWhite.png

核心代码导读

我们使用的是

Call call = client.newCall(request);

它本身就是支持异步的一个调用。 然后在得到相应的Http报文后使用一个Handler向APP主界面发起改变界面中内容的调用。

这边有一点需要注意的是OKHttp在返回的response.body()这个API,在一次请求里只能被使用一次。即如果你已经有以下一句类似的调用:

inputStream = response.body().byteStream();

你就不能再在它以下的语句中调用一次response.body()了。

自己动一下手试试看效果吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK