okhttp获取服务器响应码,OkHttp访问服务器中的xml资源

首先,添加OkHttp依赖

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

因为静态接口需要Java8才能支持使用,我们要使用静态接口,需要在build.gradle文件中添加如下配置声明,使用Java8编译

compileOptions {

sourceCompatibility JavaVersion.VERSION_1_8

targetCompatibility JavaVersion.VERSION_1_8

}

不然会出现如下异常:

错误一:

Static interface methods are only supported starting with Android N (--min-api 24): java.util.List okhttp3.Dns.lambda$static$0(java.lang.String)

Message{kind=ERROR, text=Static interface methods are only supported starting with Android N (--min-api 24):

java.util.List okhttp3.Dns.lambda$static$0(java.lang.String),sources=[Unknown source file], tool name=Optional.of(D8)}

错误二:

Invoke-customs are only supported starting with Android O (--min-api 26)

Message{kind=ERROR, text=Invoke-customs are only supported starting with Android O (--min-api 26), sources=[Unknown source file], tool name=Optional.of(D8)}

在AndroidManifest.xml中添加网络访问权限

创建工具类:

1 public class OkHttpTools {

2 //创建OkHttpClient对象

3 private final OkHttpClient client = new OkHttpClient();

4 //获取章节信息的方法

5 public String getDate(String url){

6 //构建请求

7 Request request = new Request.Builder()

8 .url(url)

9 .build();

10 //获取Response对象

11 try (Response response = client.newCall(request).execute()) {

12 //响应成功并返回响应内容

13 if (response.isSuccessful()) {

14 return response.body().string();

15 //此时代码执行在子线程,修改UI的操作使用handler跳转到UI线程

16 }

17 }catch (Exception e){

18 e.printStackTrace();

19 }

20 return " ";

21 }

22 }

Activity:在子线程中获取访问的数据,并把解析的数据通过Handler添加到适配器中

子线程:

1 new Thread(){

2 @Override

3 public void run() {

4 OkHttpTools tools = new OkHttpTools();

5 String s = tools.getDate("http://192.168.*.*:8080/resource/chapter"+id+".xml");

6 if (s!=null){

7 //s.getBytes()返回的是字节数组

8 initData(new ByteArrayInputStream(s.getBytes()));

9 handler.sendEmptyMessage(MSG_OK);

10 }

11 }

12 }.start();

initData()方法:接收流对象并进行解析数据

1 private void initData(InputStream is) {

2 try {

3 //获取解析xml的数据

4 ebl = AnalysisUtils.getExercisesInfos(is);

5 } catch (Exception e) {

6 e.printStackTrace();

7 }

8 }

Handler:进行数据的处理

1 Handler handler = new Handler(){

2 @Override

3 public void handleMessage(Message msg) {

4 if (msg.what== MSG_OK){

5 //将解析的数据添加到适配器

6 adapter.setData(ebl);

7 //刷新数据

8 adapter.notifyDataSetChanged();

9 }

10 }

11 };

标签:xml,String,supported,only,Handler,服务器,OkHttp,new

来源: https://www.cnblogs.com/chaunceyji/p/10940041.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值