首先,添加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中添加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
创建工具类:
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 };