The first line of code reading notes
WebView
- Embed a browser in the application
WebView webView = (WebView) findViewById(R.id.web_view); // Set the browser property webView.getSettings().setjavascriptenabled (true); Webview.setwebviewclient (new WebViewClient())) is displayed in the current WebView. webView.loadUrl("http://www.baidu.com");Copy the code
- Permission statement
<uses-permission android:name="android:permission:INTERNET" />
Use HTTP to access the network
HttpURLConnection
// Get HttpURLConnection instance URL = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); / / set the HTTP request method used by / / GET/POST connection. SetRequestMethod (" GET "); / / custom set connection. SetConnectTimeout (8000); connection.setReadTimeout(8000); / / get the server returns the input stream of an InputStream in = connection. The getInputStream (); // Close the HTTP connection connection.disconnect();Copy the code
- Enable the child thread to initiate an HTTP request
runOnUiThread()
Method to switch the thread to the main thread for UI operations POST
: Write out the data to be submitted before retrieving the input stream. Each piece of data must be in the form of key-pair values, used between data&
Sign offconnection.setRequestMethod("POST"); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeByte("username=admin&password=123456"); Copy the code
OkHttp
- Project Address:
https://github.com/square/okhttp
- Add the dependent
'com. Sqareup. Okhttp3: okhttp: 3.4.1 track'
- GET
// create OkHttpClient OkHttpClient client = new OkHttpClient(); // Request Request = new request.builder ().build(); // Enrich the Request object with other methods before the final build() Request Request = new request.builder ().url("www.baidu.com").build(); // Create a Call object, // Response object is the data returned by the server. Response Response = client.newCall(request).execute(); String responseData = response.body().string();Copy the code
- POST
// create OkHttpClient OkHttpClient client = new OkHttpClient(); RequestBody RequestBody = new formBody.builder.add ("username", "admin").add("password", Build () // Call post() in request.builder, Request = new Request.Builder().url("www.baidu.com").post(RequestBody).build(); Response Response = client.newCall(request).execute(); Response = client.newCall(request).execute();Copy the code
Parsing XML format data
Pull parsing
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) { case XmlPullParser.START_TAG: { if ("id".equals(nodeName)) { id = xmlPuallParser.nextText(); } else if ("name".equals(nodeName)) { name = xmlPuallParser.nextText(); } else if ("version".equals(nodeName)) { version = xmlPuallParser.nextText(); } break; } case XmlPuallParser,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 = xmlPuallParser.next(); } } catch (Exception e) { e.printStackTrace(); }}Copy the code
SAX parsing
- Usage is a bit more complex than Pull parsing and semantically clearer
public class MyHandler extends DefaultHandler { private String nodeName; private StringBuilderid; private StringBuilder name; private StringBuilder version; @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 { 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(nodeName)) { Log.d("ContentHanlder", "id is " + id.toString().trim()); Log.d("ContentHanlder", "name is " + name.toString().trim()); Log.d("ContentHanlder", "version is " + version.toString().trim()); id.setLength(0); name.setLength(0); version.setLength(0); } } @Override public void endDocument() throws SAXException { super.endDocument(); }}Copy the code
startDocument()
startElement()
characters()
endElement()
endDocument()
private void parseXMLWithSAX(String xmlData) { try { SAXParserFactory factory = SAXParserFactory().newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); ContentHandler handler = new ContentHandler(); xmlReader.setContentHandler(handler); xmlReader.parse(new InputSource(new StringReader(XmlData))); } catch (Exception e) { e.printStackTrace(); }}Copy the code
The DOM parsing
- slightly
Parse JSON data
- JSONObject, GSON, Jackson, FastJSON etc.
JSONObject
- The official offer
private void parseJSONObject(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(); }}Copy the code
GSON
- Add the dependent
'com. Google. Code. Gson: gson: 2.7'
- Parse a class to a class
Gson gson = new Gson(); Person person = gson.fromJson(jsonData, Person.class); Copy the code
- Parsing a
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType()); Copy the code
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 " + id); Log.d("MainActivity", "name is " + name); Log.d("MainActivity", "version is " + version); }}Copy the code