一、WebView
的用法
新建一个空项目
day16_WebViewTest
WebView 应用内嵌浏览器
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/web"/>
</LinearLayout>
主活动:
public class MainActivity extends AppCompatActivity {
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = findViewById(R.id.web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://bilibili.com");
}
}
setJavaScriptEnabled()
使其支持JS脚本
setWebViewClient()
网页跳转时在本控件内进行,而不是打开系统浏览器
loadUrl()
传入对应网址
网络权限声明:
<uses-permission android:name="android.permission.INTERNET"/>
运行:
二、使用HTTP
协议访问网络
新建一个
day16_NetworkTest
空项目
1、HttpURLConnection
Android团队推荐使用HttpURLConnection
发送HTTP请求,其步骤如下:
- 获取
HttpURLConnection
实例:new一个URL对象,调用openConnection()
即可 - 用实例设置请求所使用的方法,
GET
或POST
,调用setRequestMethod()
- 自由定制,设置连接超时
setConnectTimeout()
、读取的毫秒数setReadTimeout()
、消息头等等 - 获取输入流,
getInputStream()
- 最后关闭连接,
disconnect()
举个例子:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/send_request"
android:text="发送请求"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response_text"/>
</ScrollView>
</LinearLayout>
活动:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView textView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = findViewById(R.id.send_request);
textView = findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 对获取到的输入流读取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine())!= null){
response.append(line);
}
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
if (connection != null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(response);
}
});
}
}
我们在子线程内用HttpURLConnection
发出了一条HTTP请求,用BufferedReader
完成数据流的读取
用runOnUiThread()
将线程切换到主线程,再更新UI元素【Android不允许子线程UI操作】
最后更新权限:
<uses-permission android:name="android.permission.INTERNET"/>
运行:
2、OkHttp
官网:https://square.github.io/okhttp/
添加依赖:
implementation("com.squareup.okhttp3:okhttp:4.3.1")
Request
用法:
- 创建
OkHttpClient
实例:new OkHttpClient()
- 创建
Request
对象:new Request.Builder().url("").build()
- 调用实例的
newCall()
创建Call
对象,调用execute()
发送请求获取数据:Response response = client.newCall(request).execute()
- 获取返回的内容:
response.body().String()
Post
用法:
RequestBody requestBody = new FormBody.Builder()
.add("username", "admin")
.add("password", "123456")
.build();
Request request = new Request.Builder()
.url("")
.post(requestBody)
.build()
接下来和Request用法一样
主活动:
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
运行: