一,WebView的用法
活動布局的代碼:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
然後在活動頁中修改代碼:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView=(WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(
new WebViewClient()
);
webView.loadUrl("https://www.baidu.com");
}
}
menifest檔案中增權重限控制
二,使用http協定通路網絡
1,使用OkHttpClient
第一步:在app/build.gradle檔案中引入庫
implementation 'com.squareup.okhttp3:okhttp:3.14.7'
implementation 'com.squareup.okio:okio:1.17.5'
第二步:在menifest檔案中申請網絡權限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
第三步:布局修改
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/test_text"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ScrollView>
</LinearLayout>
第四步:活動頁中修改發起get請求
public class MainActivity extends AppCompatActivity {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseText=(TextView) findViewById(R.id.test_text);
//建立一個OkHttpClient執行個體
OkHttpClient httpClient = new OkHttpClient();
String url = "https://www.baidu.com/";
//建構一個request對象
Request getRequest = new Request.Builder()
.url(url)
.get()
.build();
//調用OkHttpClient建立一個Call對象
Call call = httpClient.newCall(getRequest);
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步請求,要放到子線程執行,調用它的execute方法發送請求
Response response = call.execute();
//将内容顯示到桌面上
showResponse(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
2,如果是post請求的話,就需要是這樣:
//建立一個OkHttpClient執行個體
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody=new FormBody.Builder()
.add("username","admin")
.add("password","123456")
.build();
Request request=new Request.Builder()
.url("http://www.baidu.com")
.post(requestBody)
.build();
//調用OkHttpClient建立一個Call對象
Call call = httpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
//同步請求,要放到子線程執行,調用它的execute方法發送請求
Response response = call.execute();
//将内容顯示到桌面上
showResponse(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
三,解析XML格式檔案
在網絡上傳輸的資料通常是有兩種格式XML和JSON.
1,資料從哪裡來
我們可以搭建一個web伺服器,然後在這個伺服器上提供一段XML格式的資料。接着在我們的程式裡面取通路這個伺服器,再對得到的XML文本進行解析。
建立一個get_data.xml檔案:
<apps>
<app>
<id>1</id>
<name>Google maps</name>
<version>1.0</version>
</app>
<app>
<id>2</id>
<name>Chrome</name>
<version>2.1</version>
</app>
<app>
<id>3</id>
<name>Google Play</name>
<version>2.3</version>
</app>
</apps>
放置到nginx檔案中(nginx下載下傳使用參考:https://blog.csdn.net/weixin_42349568/article/details/129245335?spm=1001.2014.3001.5501):
然後浏覽器通路即可得到這個:
2,Pull解析xml
public class MainActivity extends AppCompatActivity {
TextView responseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
responseText=(TextView) findViewById(R.id.test_text);
new Thread(new Runnable() {
@Override
public void run() {
try {
//建立一個OkHttpClient執行個體
OkHttpClient httpClient = new OkHttpClient();
Request request=new Request.Builder()
.url("http://172.20.10.8/get_data.xml")
.build();
//同步請求,要放到子線程執行,調用它的execute方法發送請求
Response response = httpClient.newCall(request).execute();
String responseData=response.body().string();
Log.d("TAG", responseData);
parseXMLWithPull(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private String parseXMLWithPull( String xmlData){
StringBuilder stringBuilder = new StringBuilder();
try {
//建立工廠
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//擷取執行個體
XmlPullParser xmlPullParser = factory.newPullParser();
//向解析器添加xml資料
xmlPullParser.setInput(new StringReader(xmlData));
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();
stringBuilder.append("id:" + id + " ");
} else if ("name".equals(nodeName)) {
name = xmlPullParser.nextText();
stringBuilder.append("name:" + name + " ");
} else if("version".equals(nodeName)){
version = xmlPullParser.nextText();
stringBuilder.append("version:" + version + " ");
}
break;
}
case XmlPullParser.END_TAG: {
stringBuilder.append("\n");
break;
}
default:
}
try {
eventType = xmlPullParser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("result:\n" + stringBuilder.toString());
return stringBuilder.toString();
}
}
中間如果遇到了網絡通路有問題的情況,可以參考這篇部落格:https://blog.csdn.net/java558/article/details/111357872。
實作的效果:
四,解析JSON格式檔案
1,建立json檔案
[{"id":"5","version":"5.5","name":"clash of class"},
{"id":"6","version":"7.2","name":"clash of class"},
{"id":"7","version":"8.3","name":"clash of class"}]
2,使用GSON來解析json
第一步:引入依賴:
第二步:建立app類
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getVersion() {
return 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 class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
//建立一個OkHttpClient執行個體
OkHttpClient httpClient = new OkHttpClient();
Request request=new Request.Builder()
.url("http://172.20.10.8/get_data.json")
.build();
//同步請求,要放到子線程執行,調用它的execute方法發送請求
Response response = httpClient.newCall(request).execute();
String responseData=response.body().string();
parseJSONWithGSON(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithGSON(String jsonData){
Gson gson=new Gson();
List<App> appList=gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
for (int i=0;i<appList.size();i++){
App app=appList.get(i);
String name = app.getName();
Log.d("TAG", name);
}
}
}