WebView
brief introduction
- It is generally used to load some network interfaces
- Android is a high-performance browser with built-in webkit kernel, and WebView is a control encapsulated on this basis. WebView can be simply regarded as a browser control that can be nested on the interface!
method
- WebChromeClient
Assist WebView in handling Javascript dialog boxes, website icons, website title s, loading progress, etc
method | effect |
onJsAlert(WebView view,String url,String message,JsResult result) | Handling Alert dialog in Js |
onJsConfirm(WebView view,String url,String message,JsResult result) | Process the Confirm dialog in Js |
onJsPrompt(WebView view,String url,String message,String defaultValue,JsPromptResult result) | Process Prompt dialog in Js |
onProgressChanged(WebView view,int newProgress) | Called when the loading progress bar changes |
onReceivedIcon(WebView view, Bitmap icon) | Get the icon of the web page |
onReceivedTitle(WebView view, String title) | Get the title of the page |
- WebViewClient
Assist WebView to handle various notification and request events
method | effect |
onPageStared(WebView view,String url) | Notify the main program that the web page starts loading |
onPageFinished(WebView view,String url,Bitmap favicon) | Notify the main program that the web page is loaded |
doUpdateVisitedHistory(WebView view,String url,boolean isReload) | Update history |
onLoadResource(WebView view,String url) | Notifies the main program that WebView is about to load the resource with the specified url |
onScaleChanged(WebView view,float oldScale,float newScale) | Called when the zoom of the ViewView changes |
shouldOverrideKeyEvent(WebView view,KeyEvent event) | Controls whether WebView processes the key pressing time. If true is returned, WebView does not process it, and if false is returned, WebView processes it |
shouldOverrideUrlLoading(WebView view,String url) | Controls the processing of newly loaded URLs. Returning true means that the main program does not process WebView. Returning false means that WebView will process it |
onReceivedError(WebView view,int errorCode,String description,String failingUrl) | Called when an unrecoverable error message is encountered |
- WebSettings
WebView related configuration settings, such as setJavaScriptEnabled() setting whether JS script execution is allowed
method | effect |
getSettings() | Returns a WebSettings object to control the property setting of WebView |
loadUrl(String url) | Loads the specified Url |
loadData(String data,String mimeType,String encoding) | Load the specified data into WebView Using "data:" as the tag header, this method cannot load network data Where mimeType is the data type, such as textml, image / jpeg Encoding is the encoding method of characters |
loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) | More powerful than loadData above |
setWebViewClient(WebViewClient client) | Specify a WebViewClient object for WebView WebViewClient can assist WebView in handling various notifications, requests and other events. |
setWebChromeClient(WebChromeClient client) | Specify a WebChromeClient object for WebView. WebChromeClient is specially used to assist WebView in processing js dialog boxes, website title s, website icons, loading progress bars, etc |
example
- xml
<WebView android:id="@+id/web_view" android:layout_width="409dp" android:layout_height="729dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
- MainActivity
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView webView = findViewById(R.id.web_view); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl("https://www.baidu.com"); } }
- Manifest
On Android 9 After 0, the url does not support plaintext format, so either encrypt https, add a line of Android: usesclleartexttraffic = "true" in the application (but not), or reduce the SDK version
<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:usesCleartextTraffic="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
- Download address
DoSomeAndroidTest/WebView at main · qricis/DoSomeAndroidTest · GitHub
Network request mode
- In the past, there were generally two ways to send Http requests on Android: HttpURLConnection and HttpClient. However, due to the excessive number of API s of HttpClient, Android 6 0 has been completely removed from the system
// HttpURLConnection // Get the instance URL url = new URL("http://baidu.com"); HttpUriConnection connection = (HttpURLConnection) url.openConnection(); // Set the method used for the request (get / post). Get indicates that you want to obtain data from the server, and post indicates that you want to submit data to the server connection.setRequestMethod("GET") // connection timed out connection.setConnectTimeout(8000); // Number of milliseconds read timeout connection.setReadTimeout(8000); // Gets the input stream returned by the server InputStream in = connection.getInputStream(); // Call the disconnect() method to close the http connection connection.disconnect()
- xml
<Button android:id="@+id/send_request" android:layout_width="163dp" android:layout_height="0dp" android:text="@string/sendrequest" android:onClick="sendResquest" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent="0.08" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginTop="1dp" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent="0.9" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/send_request" app:layout_constraintVertical_bias="1.0"> <TextView android:id="@+id/response_text" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView>
- Manifest
<uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
- MainActivity
public class MainActivity extends AppCompatActivity { TextView responseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); responseText = findViewById(R.id.response_text); } public void sendResquest(View view) { sendRequestWithHttpURLConnection(); } private void sendRequestWithHttpURLConnection() { //Start a thread to initiate a network request 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(); //How to submit data to the server /*connection.setRequestMethod("POST"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes("username=admin&password=123456");*/ //Read the obtained input stream 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() { //Perform UI operations here and display the results on the interface responseText.setText(response); } }); } }
OkHttp
- build.gradle
implementation 'com.squareup.okhttp3:mockwebserver:4.8.1'
- MainActivity
private void sendRequestWithOkHttp() { new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://www.baidu.com") .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); showResponse(responseData); } catch (Exception e) { e.printStackTrace(); } } }).start(); }
- Upgraded version (parsing data)
private void parseXMLWithPull(String xmlData) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser = factory.newPullParser(); 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) { //Start parsing a node 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; } //Finish parsing a node case XmlPullParser.END_TAG:{ if ("app".equals(nodeName)) { Log.d("MainActivity","id is " + id); Log.d("MainActivity","name is " + name); Log.d("MainActivity","version is " + version); } break; } default: break; } eventType = xmlPullParser.next(); } } catch (Exception e) { e.printStackTrace(); } } private void parseXMLWithSAX(String xmlData) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); ContentHandler handler = new ContentHandler(); //Set the instance of ContentHandler to XMLReader xmlReader.setContentHandler(handler); //Start parsing xmlReader.parse(new InputSource(new StringReader(xmlData))); } catch (Exception e) { e.printStackTrace(); } } 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("MainActivity","id is " + id); Log.d("MainActivity","name is " + name); Log.d("MainActivity","version is " + version); } } catch (Exception e) { e.printStackTrace(); } } private void parseJSONWithGson(String jsonData) { Gson gson = new Gson(); List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType()); for (App app : appList) { Log.d("MainActivity","id is " + app.getId()); Log.d("MainActivity","name is " + app.getName()); Log.d("MainActivity","version is " + app.getVersion()); } } private void showResponse(final String response) { runOnUiThread(new Runnable() { @Override public void run() { //Perform UI operations here and display the results on the interface responseText.setText(response); } }); }
Download address
DoSomeAndroidTest/NetworkTest at main · qricis/DoSomeAndroidTest · GitHub