目录
WebView的用法
控件,借助它我们可以在自己的应用程序中嵌入一个浏览器
1.创建WebView控件
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"/>
2.获取WebView对象,设置相关属性
WebView webView = (WebView)findViewById(R.id.webView);
//webView.getSettings()方法可设置一些浏览器的属性
webView.getSettings().setJavaScriptEnabled(true);
//设置WebView支持JavaScript脚本
webView.setWebViewClient(new WebViewClient());
//当需要从一个网页跳转到另一个网页时,我们希望目标网页在当前WebView中显示,而不是打开系统浏览器
webView.loadUrl("http://www.baidu.com"); //传入要打开的网址
3.添加权限
<uses-permission android:name="android.permission.INTERNET"/>
此时运行发现打不开网页,需要设置android:usesCleartextTraffic=“true”
<application
...
android:usesCleartextTraffic="true"
...
</application>
由于这里要使用明文网络流量所以要设置成true
android:usesCleartextTraffic
指示应用程序是否打算使用明文网络流量,例如明文HTTP。目标API级别为27或更低的应用程序的默认值为“ true”。面向API级别28或更高级别的应用默认为“ false”。
当属性设置为“ false”时,平台组件(例如,HTTP和FTP堆栈,DownloadManager和MediaPlayer)将拒绝应用程序使用明文流量的请求。
强烈建议第三方库也采用此设置。避免明文通信的主要原因是缺乏机密性,真实性和防篡改保护;网络攻击者可以窃听所传输的数据,并且还可以对其进行修改而不会被检测到
使用HTTP协议访问网络
HttpURLConnection
从服务器获取数据
-
获取HttpURLConnection实例
这里是借助URL对象获取
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
- 设置请求所用的方法
GET:从服务器获取数据
POST:提交数据给服务器
connection.setRequestMethod("GET");
- 获取服务器的返回流,读取数据
完整代码如下:
private void sendRequestWithHttpURLConnection() {
//网络请求是费时操作,所以要开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL("http://www.baidu.com");
connection =(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET"); //设置HTTP请求所用的方法
connection.setConnectTimeout(8000); //设置连接超时的毫秒数
connection.setReadTimeout(8000); //设置读取超时的毫秒数
InputStream in = connection.getInputStream(); //获取到服务器返回的输入流
//对输入流进行读取
bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String Line;
while ( (Line = bufferedReader.readLine()) != null){
stringBuilder.append(Line);
}
//shouResponse(stringBuilder.toString());
}catch (Exception e){
e.printStackTrace();
}finally {
if(connection != null)
connection.disconnect();
if(bufferedReader != null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
提交数据给服务器
方法和上面一样,只是把GET改为POST
private void acceptRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedWriter writer = null;
try {
URL url = new URL("http://www.baidu.com");
connection =(HttpURLConnection) url.openConnection();
connection.setRequestMethod("STOP");
//获取输出流用于输出数据
OutputStream os = connection.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(os);
dataOutputStream.writeBytes("username=admin&password=123456");
/*
String st =