使用網路技術
??本章主要講述如何在手機端使用HTTP和服務器進行網路互動,并對服務器回傳的資料進行決議,這也是Android中最常使用到的網路技術
01 WebView的用法
??WebView控制元件,借助它我們就可以在自己的應用程式里嵌入一個瀏覽器,從而非常輕松地展示各種各樣的網頁,
//需在manifest.xml檔案中添加
//application屬性:android:usesCleartextTraffic="true"
//權限<uses-permission android:name="android.permission.INTERNET" />.
//使用百度進行搜索后會有net:err_unknown_url_scheme錯誤
WebView webView = (WebView) findViewById(R.id.webView);
//讓其支持JavaScript腳本
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.baidu.com");
權限允許
<uses-permission android:name="android.permission.INTERNET" />
在manifest.xml中添加application的屬性
<application
android:usesCleartextTraffic="true"
/>
02 使用HTTP協議訪問網路
??作業原理特別簡單,就是客戶端向服務器發出一條HTTP請求,服務器收到請求之后會回傳一些資料給客戶端,然后客戶端再對這些資料進行決議和處理.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//發送http請求
Button sendHttp = (Button) findViewById(R.id.sendHttp);
sendHttp.setOnClickListener(this);
responseText = (TextView) findViewById(R.id.responseText);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.sendHttp){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//2 獲取鏈接
URL url = new URL("https://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
//3 鏈接設定
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//4 對獲取到的輸入流進行讀取
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) {
//5 通過runOnUiThread在主執行緒進行UI操作
runOnUiThread(new Runnable() {
@Override
public void run() {
//在這里進行UI操作
responseText.setText(response);
}
});
}
}
權限
<uses-permission android:name="android.permission.INTERNET" />
03 使用OkHttp
匯入依賴
implementation 'com.squareup.okhttp3:okhttp:4.1.0'
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//發送http請求
Button sendHttp = (Button) findViewById(R.id.sendHttp);
sendHttp.setOnClickListener(this);
responseText = (TextView) findViewById(R.id.responseText);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.sendHttp){
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
//2 獲得鏈接
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url("http://www.baidu.com")
.build();
//3 接收結果
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) {
//4 通過runOnUiThread在主執行緒進行UI操作
runOnUiThread(new Runnable() {
@Override
public void run() {
//在這里進行UI操作
responseText.setText(response);
}
});
}
}
04 決議XML資料-PULL
Ubuntu下安裝apche
sudo apt-get install apache2 //其他配置自行設定
在var/www/html下建立get_data.xml
<apps>
<app>
<id>1</id>
<name>google maps</name>
<version>1.0</version>
</app>
</apps>
新建xml/network_config.xml讓程式允許http
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
manifest中application屬性添加
android:networkSecurityConfig="@xml/network_config
private void sendRequestWithOkHttp() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
//2 獲得鏈接
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url("http://10.92.36.25/get_data.xml") //網址10.0.2.2或者自己的ip地址
.build();
//3 接收結果
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseXMLWithPull(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//決議xml
private void parseXMLWithPull(String xmlData) {
//進行決議
XmlPullParserFactory factory = null;
try {
//通過工廠獲得XmlPullParser物件
factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
//setInput將服務器回傳的XML資料進行決議
xmlPullParser.setInput(new StringReader(xmlData));
//getEventType()可以得到當前決議事件,然后在一個while回圈中不斷決議
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while(eventType != XmlPullParser.END_DOCUMENT){
String nodeName = xmlPullParser.getName();
switch (eventType){
//開始決議節點<>
case XmlPullParser.START_TAG: {
if ("id".equals(nodeName)) {
id = xmlPullParser.nextText();
} else if ("name".equals(nodeName)) {
name = xmlPullParser.nextText();
} else if ("version".equals(nodeName)) {
version = xmlPullParser.nextText();
}
break;
}
//完成決議某個節點</>
case XmlPullParser.END_TAG:{
if ("app".equals(nodeName)){
Log.d(TAG, "id is "+ id);
Log.d(TAG, "name is "+ name);
Log.d(TAG, "version is "+ version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
05 決議XML資料-SAX
新建類繼承DefaultHandler
public class ContentHandler extends DefaultHandler {
private static final String TAG = "ContentHandler";
private String nodeName;
private StringBuilder id;
private StringBuilder name;
private StringBuilder version;
//開始document決議時呼叫
@Override
public void startDocument() throws SAXException {
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
}
//開始決議某個節點時呼叫
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//記錄當前節點名
nodeName = localName;
}
//獲取節點中內容時呼叫
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
//根據當前節點名判斷將內容添加到哪一個stringbuilder物件中
if ("id".equals(nodeName)) {
id.append(ch,start,length);
} else if ("name".equals(nodeName)) {
name.append(ch,start,length);
} else if ("version".equals(nodeName)) {
version.append(ch,start,length);
}
}
//完成決議某個節點時呼叫
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("app".equals(localName)){
Log.d(TAG, "id is "+ id.toString().trim());
Log.d(TAG, "name is "+ name.toString().trim());
Log.d(TAG, "version is "+ version.toString().trim());
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
//完成整個XML決議時呼叫.
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
MainActivity.java
private void sendRequestWithOkHttp() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
//2 獲得鏈接
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url("http://10.92.36.25/get_data.xml") //網址10.0.2.2或者自己的ip地址
.build();
//3 接收結果
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseXMLWithSAX(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//SAX決議xml
private void parseXMLWithSAX(String xmlData) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler handler = new ContentHandler();
//將contenthandler的實體放到XMLReader中
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(xmlData)));
} catch (Exception e) {
e.printStackTrace();
}
}
??首先給id、name和version節點分別定義了一個StringBuilder物件,并在**startDocument()**方法里對它們進行了初始化,每當開始決議某個節點的時候,**startElement()方法就會得到呼叫,其中localName引數記錄著當前節點的名字,這里我們把它記錄下來,接著在決議節點中具體內容的時候就會呼叫characters()方法,我們會根據當前的節點名進行判斷,將決議出的內容添加到哪一個StringBuilder物件中,最后在endElement()**方法中進行判斷,如果app節點已經決議完成,就列印出id、name和version的內容,需要注意的是,目前id、name和version中都可能是包括回車或換行符的,因此在列印之前我們還需要呼叫一下trim()方法,并且列印完成后要將StringBuilder的內容清空,不然的話會影響下一次內容的讀取,
06 決議JSON資料-JSONObject
同樣先在var/www/html(apache默認根目錄)下創建get_data.json
private void sendRequestWithOkHttp() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
//2 獲得鏈接
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url("http://10.92.36.25/get_data.json") //網址10.0.2.2或者自己的ip地址
.build();
//3 接收結果
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWithJSONObject(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//決議JSON
private void parseJSONWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
Log.d(TAG, "id is "+ id);
Log.d(TAG, "name is "+ name);
Log.d(TAG, "version is "+ version);
}
} catch (Exception e) {
e.printStackTrace();
}
}
07 決議JSON資料-GSON
<!--添加依賴-->
implementation 'com.google.code.gson:gson:2.8.5'
private void sendRequestWithOkHttp() {
//1 開啟執行緒發起網路請求
new Thread(new Runnable() {
@Override
public void run() {
try {
//2 獲得鏈接
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().
url("http://10.92.36.25/get_data.json") //網址10.0.2.2或者自己的ip地址
.build();
//3 接收結果
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWithGSON(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
//決議JSON
private void parseJSONWithGSON(String jsonData) {
try {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData,new TypeToken< List<App> >(){}.getType() );
for (App app : appList){
Log.d(TAG, "id is "+ app.getId());
Log.d(TAG, "name is "+ app.getName());
Log.d(TAG, "version is "+ app.getVersion());
}
} catch (Exception e) {
e.printStackTrace();
}
}
得新建一個類用于映射
public class App {
private String id;
private String name;
private String version;
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/293644.html
標籤:其他
