一、WebView控件的使用
使用WebView控件可以讓我們在應用程序中嵌入一個瀏覽器,以便更好的展示各種網頁內容。
下面是一個測試的小案例:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="cn.edu.hznu.webviewtest.MainActivity">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
MainActivity.java
package cn.edu.hznu.webviewtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到WebView的實例
WebView webView=(WebView)findViewById(R.id.web_view);
//調用getSettings()方法,設置瀏覽器的屬性——支持javaScript腳本
webView.getSettings().setJavaScriptEnabled(true);
//調用setWebViewClient方法,傳入WebViewClient的實例
webView.setWebViewClient(new WebViewClient());
//調用loadUrl方法,傳入網址
webView.loadUrl("http://www.baidu.com");
}
}
此外,我們需要注意:由於程序中使用到了網絡的功能,我們需要在AndroidManifest.xml
中聲明權限:
<uses-permission android:name="android.permission.INTERNET" />
二、使用HTTP協議訪問網絡
2.1、使用HttpURLConnection
具體的使用方法如下:
1、 得到HttpURLConnection的實例。
URL url=new URL(“http://www.baidu.com”);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
2、 設置HTTP請求所使用的方法(GET和POST)
conn.setRequestMethod(“GET”);
3、 根據需要設置一些屬性,如連接超時、讀取超時等。
conn.setConntectionTimeout(8000);
conn.setReadTimeout(8000);
4、 獲取服務器返回的輸入流,然後對輸入流進行讀取數據。
InputStream in=conn.getInputStream();
5、 最後將HTTP連接關閉。
conn.disconnection();
測試的小案例:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="cn.edu.hznu.ex6.MainActivity">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="點擊按鈕"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
MainActivity.java
package cn.edu.hznu.ex6;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (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("http://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 (Exception 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() {
// 在這裏進行UI操作,將結果顯示到界面上
responseText.setText(response);
}
});
}
}
注意:不要忘記在AndroidManifest.xml
中聲明網絡權限:
<uses-permission android:name="android.permission.INTERNET" />
下面我們運行項目,點擊 “點擊按鈕”後:
三、使用OkHttp
在使用之前,由於okhttp不是原生庫,需要添加依賴,在app/build.gradle文件中的 dependencies 閉包中添加依賴:
compile 'com.squareup.okhttp3:okhttp:3.4.1'
具體的使用如下:
1、創建OKHttpClient的實例。
OKHttpClient client=new OKHttpClient();
2、創建Request對象,用以發起HTTP請求。
Request request=new Request.Builder().url("http://baidu.com").build();
3、發送請求,獲取服務器返回的數據。
Response response=client.newCall(request).execute();
4、獲取返回數據的具體內容。
String responseData=response.body().string();
測試的小案例:
activaty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="cn.edu.hznu.ex6.MainActivity">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="點擊按鈕"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
MainActivity.java
package cn.edu.hznu.ex6;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
// 指定訪問的服務器地址是電腦本機
.url("http://10.0.2.2/get_data.json")
.build();
Response response = client.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() {
// 在這裏進行UI操作,將結果顯示到界面上
responseText.setText(response);
}
});
}
在上面的佈局文件中,主要用到的控件:
- ScrollView用於滾動查看內容。
- TextView用來顯示服務器返回的數據。
- Button用來發送HTTP請求。