WebView 使用 SOP
activity.xml
1 | <?xml version="1.0" encoding="utf-8"?> |
MainActivity.java
1 | WebView mWebView = findViewById(R.id.web_view); |
AndroidManifest.xml
1 | <uses-permission android:name="android.permission.INTERNET"/> |
特殊注意事项
子线程中完成服务器结束响应后的回调
在获取到服务器响应数据后, 可以对其进行解析和处理.
但是网络请求是耗时操作, 需要放在子线程中进行.
WebView_Http 基本介绍
Client 向 Server 发一条请求 ,
Server 收到后返回一些数据给 Client ,
Client 对数据进行解析和处理
HttpURLConnection SOP
实例化对象
1
2URL url = new URL("http://www.iyounix.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();设置 Http 请求所使用的方法
GET 希望从服务器获取数据
POST 希望提交数据给服务器1
2
3
4
5
6connection.setRequestMethod("GET");
connection.setRequestMethod("POST");
// 设置连接超时
connection.setConnectTimeout(8000);
// 设置读取超时
connection.setReadTimeout(8000);获取服务器返回的输入流 getInputStream()
1
InputStream in = connection.getInputStream();
获取到的输入流可以拿来 进行 各种骚操作.
example:1
2
3
4
5
6
7
8
9
10InputStream in = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line; //读到读完为止
while ((line = reader.readLine()) != null) {
response.append(line);
}
// Android 的子线程中是无法进行 UI 界面的刷新的
// 通过调用 runOnUiThread 回到主线程进行 UI 的刷新
showResponse(response.toString());
提交数据给服务器 getOutputStream()
1
2
3connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin & password=123456");关闭
1
connection.disconnect();
WebView_OKHttp 基本介绍
Square 公司开发.
https://github.com/square/okhttp
OKHttp SOP
build.gradle
添加依赖1
2
3dependencies{
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
}
MainActivity.java
1 | // 1. 创建 OkHttpClient 实例 |