9.1 WebView (控件之一)的用法
WebView控件可以帮我们在自己的应用程序里嵌入一个浏览器,从而非常轻松地展示各种各样的网页。下面我们就来实践一下
然后我们修改MainActivity中的代码:
①这里调用getSettings()方法可以设置一些浏览器的属性,其中setJavaScriptEnabled()方法让WebView支持JavaScript的脚本的;
②调用setWebViewClient()方法并传入一个实例,其作用是:当需要从一个网页跳转到另一个网页时,我们希望目标网页仍然在当前WebView中显示,而不是打开系统浏览器
③调用loadUrl()方法并传入网页地址显示网页
最后,声明权限:
<uses-permission android:name="android.permission.INTERNET" />
这样就实现了一个简单的网页界面的显示
9.2 使用HTTP协议访问网络
HTTP工作原理:
- ①客户端向服务器发出一条HTTP请求;
- ②服务器收到请求之后会返回一些数据给客户端;
- ③然后客户端再对这些数据进行解析和处理
9.2.1 使用HttpURLConnection
使用步骤: - ①首先获取到HttpURLConnection的实例;
- ②得到HttpURLConnection实例之后,设置一下HTTP请求所使用的方法,一般右GET和POST方法,前者表示希望从服务器那里获取数据,后者表示希望提交数据给服务器
- ③接下来就是自由定制,如设置连接超时、读取超时的毫秒数、以及服务器希望得到的一些消息头等
- ④接着再调用getInputStream()方法获取到服务器返回的输入流,对输入流进行读取
- ⑤最后调用disconnect()方法将HTTP连接关闭
下面是一个实例代码:
<com.google.android.material.button.MaterialButton
android:id="@+id/btn_essential_information_test"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http test"
tools:ignore="MissingConstraints">
</com.google.android.material.button.MaterialButton>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textview.MaterialTextView
android:id="@+id/et_essential_information_test"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.material.textview.MaterialTextView>
</ScrollView>
-
- 这里使用了一个新的控件ScrollView——以滚动的形式查看屏幕外的那部分内容;
此外,Button用于发送HTTP请求;
TextView用于将服务器返回的数据显示出来。
- 这里使用了一个新的控件ScrollView——以滚动的形式查看屏幕外的那部分内容;
-
- 然后修改MainActivity中的代码:
private Button mbtn_essential_information_test;
private TextView met_essential_information_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essential_information);
mbtn_essential_information_test = (Button)findViewById(R.id.btn_essential_information_test);
met_essential_information_test = (TextView)findViewById(R.id.et_essential_information_test);
mbtn_essential_information_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendhttpURLConnection();
}
});
}
private void sendhttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader = null;
try {
/*
* HttpURLConnection的基本用法
*/
//1、获取实例
URL url = new URL("https:/www.baidu.com");
httpURLConnection = (HttpURLConnection)url.openConnection();
//2、设置请求所使用的方法
httpURLConnection.setRequestMethod("GET");
//3、自由定制
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
//4、对服务器传过来的数据进行读取
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line = bufferedReader.readLine())!=null){
stringBuilder.append(line);
}
showResponse(stringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭输入流
if(bufferedReader != null){
try {
bufferedReader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (httpURLConnection != null){
//UI操作,将服务端传回的内容展示到界面上
httpURLConnection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
met_essential_information_test.setText(response);
}
});
}
- ①我们在Send Requ按钮点击事件里调用了sendRequestWithHttpURLConnection()方法
- ②在sendRequestWithHttpURLConnection()方法中开启了一个子线程
- ③在子线程中,发送请求,获取输入流,通过BufferedReader对返回的输入流进行读取
- ④将读取到的结果传到showResponse()方法里面,在该方法中将返回的数据显示到界面上
最后,声明权限:
<uses-permission android:name="android.permission.INTERNET" />
9.2.2 使用OkHttp
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'
添加了上述依赖会自动下载两个库,一个是OkHttp库,一个是Okio库,后者是前者的通信基础
使用步骤:
- ①首先获取到OkHttpClient的实例;
- ②接下来创建一个Request对象来发送HTTP请求
- ③在build()方法前连缀很多其他的方法来丰富这个Request对象
- ④接着再调用OkHttpClient的newCall()方法来创建一个Call对象,并调用他的execute()方法来发送请求并获取服务器返回的数据,其中Response对象就是服务器返回的数据
- 如果是发起一条POST请求会比GET请求稍微复杂些
- ⑤接下来的操作就和GET请求一样
我们修改一下MainActivity的代码:
private Button mbtn_essential_information_test;
private TextView met_essential_information_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essential_information);
mbtn_essential_information_test = (Button)findViewById(R.id.btn_essential_information_test);
met_essential_information_test = (TextView)findViewById(R.id.et_essential_information_test);
mbtn_essential_information_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendhttpURLConnection();
}
});
}
private void sendhttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
try {
/*
* OkHttp的基本用法
*/
//1、创建实例
OkHttpClient okHttpClient = new OkHttpClient();
//2、发起一条HTTP请求
Request request = new Request.Builder().url("https:/www.baidu.com").build();
//3、发送请求并获取服务器返回的数据
Response response = okHttpClient.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
met_essential_information_test.setText(response);
}
});
}
这样就差不多实现了OkHttp的用法了
9.3 解析XML格式数据
基本概念
- 1、每个需要访问网络的应用程序都会有一个自己的服务器
- 2、我们一般都会在网络上传输一些格式化后的数据给服务器(或另一个程序),服务器(或另一个程序)就可以按照相同的结构规格进行解析,从而取出他想要的那部分内容
- 3、在网络上传输数据时最常用的格式有两种:XML和JOSN格式
首先我们搭建一个最简单的Web服务器,这样我们在这个服务器上提供一段XML文本,然后我们在我们的程序里去访问这个服务器,再对得到的XML文本进行解析。我们搭建好服务器之后,在Web服务器的文件中加入如下XML格式的内容:
这样一个XML文件就搭建好了,接下来就开始解析:
9.3.1 Pull解析方式
现在我们来修改MainActivity中的代码:
①首先将HTTP请求的地址改成了电脑本机的IP地址
②我们通过调用parseXMLWithPull()方法来解析服务器返回的数据
③在parseXMLWithPull()方法中,首先获取到一个XmlPullParserFactory的实例,借助这个实例得到XmlPullParser对象;然后调用setInput()方法将服务器返回的XML数据设置进去开始解析;通过getEventType()方法可以得到当前的解析事件。通过while循环进行解析,当循环跳出时,调用next()方法后可以获取下一个解析事件
我们测试一下:
9.3.2 SAX解析方式
9.4 解析JSON格式数据
比起XML,JSON的主要优势在于它的体积更小,在网络上传输的时候更省流。缺点就是他的语义性比较差
9.4.1 使用JSONObject
9.4.2 使用GSON
GSON依赖
implementation 'com.google.code.gson:gson:2.8.6'
9.5 小结
1、WebView的基本使用方法(在程序中嵌入一个浏览器)
2、HTTP工作原理
3、HttpURLConnection、OkHttp的使用步骤
4、解析XML格式数据的两种方法:Pull 、 SAX
5、解析JOSN格式数据的两种方式:JSONObject 、 GSON