一、WebView的使用
1 | WebView webView = (WebView) findViewById(R.id.web_view); |
setJavaScriptEnabled(true):让WebView支持JavaScript脚本
setWebViewClient():将网页在当前WebView中显示
使用网络时需要加入权限声明:在Androidmanifest.xml中添加声明”<uses-permission android:name=”android.permission.INTERNET” />”
二、OkHttp的使用
添加OkHttp库的依赖
在app/build.gradle中的dependencies的闭包中添加implementation “com.squareup.okhttp3:okhttp:4.9.1”
创建OkHttpClient实例
若是HTTP请求则再创建一个Request对象;
调用OkHttpClient的newCall方法创建一个Call对象;
调用execute方法发送请求并获取服务器返回数据。(GET请求)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32private void showResponse(final String response) {
runOnUiThread(new Runnable() {
public void run() {
//这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
});
}
public void onClick(View view) {
sendRequestWithOkHttp();
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://www.baidu.com").build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}若是POST请求,需要先构建一个Request Body对象来存放待提交的参数,然后在Request.Builder中调用post方法,并将RequestBody对象传入:
1
2RequestBody requestBody = new FormBody.Builder().add("username","admin").add("password","123456").build();
Request request = new Request.Builder().url("http:www.baidu.com").post(requestBody).build();
三、解析JSON数据
使用官方提供的JSONObject
1 | private void parseJSONWithJSONObject(String jsonData) { |
使用GSON
1 | private void parseJSONWithGSON(String jsonData) { |
四、将网络操作提取到一个公用类
1 | public class HttpUtil { |
在调用sendOkHttpRequest方法时
1 | Http.sendOkHttpRequest("http://www.baidu.com", new okhttp3.Callback() { |