Android
Using HttpURLConnection
First, get an example of using HttpURLConnection: new puts out a Url object and enters the network address of the target, then calls url.. Openconnection() method is enough
URL url=new URL("http://www.baidu.com"); HttpURLConnection connection=(HttpURLConnection) url.openConnection();
After obtaining the instance, we can set the methods used for HTTP requests. The main common methods are GET and POST. GET indicates that you want to GET data from the server, while POST indicates that you want to submit data to the server.
It is written as follows:
connection.setRequestMethod("GET");
Then you can customize freely, such as setting connection timeout, reading timeout milliseconds, and the server wants to get some message headers. In short, this part is written according to your actual situation. Examples:
connection.setconnectTimeout(8000); connection.setReadTimeout(8000);
Then call getInputStream() method to get the input stream returned by the server, and then read the input stream.
InputStream in =connection.getInputStream();
Finally, you can use the disconnect () method to close the HTTP connection
connection.disconnect();
Example:
package com.example.networktest; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; 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{ private static final String TAG = "MainActivity"; TextView responseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.send_request).setOnClickListener(this); responseText=findViewById(R.id.respose_text); } @Override public void onClick(View v) { if (v.getId()==R.id.send_request){ sendRequestWithHttpURLConnection(); Log.d(TAG, "onClick: 1"); } } 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("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()); Log.d(TAG, "run: "+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(String response) { runOnUiThread(new Runnable() {//Because Android does not allow UI operations in child threads, we need to switch the thread to the main thread through the runOnUiThread () method, and then update the UI elements @Override public void run() { responseText.setText(response); } }); } }
Using OKHttp
OkHttp's project home page address: https://github.com/square/okhttp
-
Add dependency: [external chain]
-
Specific usage
Create an instance of OKHttPClient
OKHttClient client = new OKHttClient();
If you want to initiate an HTTP Request, you need to create a Request object:
Request request =new Request.Builder().build();
The above code just creates an empty Request object and has no practical effect. We can connect many other methods to enrich the Request object before the final build () method. For example, we can set the target network address through the url () method, as shown below:
Request request = new Request.Builder() .url("http://www/baidu.com") .build();
After that, we call the newCall () method of OKHttClient to create a Call object and call its execute () method to send the request and get the data returned by the server, which is written as follows:
Response response = client.newCall(request).execute();
Response is the data returned by the server. We can use the following methods to get the specific returned content:
String data =response.body().String();
Post request:
//First, build a RequestBody object to store the submitted parameters RequestBody requestBody=new FormBody.Builder() .add("username","admin") .add("password","123456") .build(); //The post () method is invoked in Request and the requestBody parameter is passed in. Request request = new Request.Builder() .url("http://www/baidu.com") .post(requestBody) .build(); //After that, the operation is the same as above. Just send the request with execute () and get the data returned by the server
Example:
... public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private static final String TAG = "MainActivity"; TextView responseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.send_request).setOnClickListener(this); responseText=findViewById(R.id.respose_text); } @Override public void onClick(View v) { if (v.getId()==R.id.send_request){ // sendRequestWithHttpURLConnection(); sendRequestWithOKHttp(); Log.d(TAG, "onClick: 1"); } } private void sendRequestWithOKHttp() { new Thread(() -> { try { OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url("http://www.baidu.com").build(); Response response = client.newCall(request).execute(); String data= Objects.requireNonNull(response.body()).string(); showResponse(data); }catch (IOException e) { e.printStackTrace(); } }).start(); } private void showResponse(String response) { runOnUiThread(() -> responseText.setText(response)); } }
Parsing xml
Use Tomacat to build a server, provide an xml text on this server, and then access and parse it through the program
So we create an htdos folder in Webapps and a get folder in this folder_ data. XML file.
<apps> <app> <id>1</id> <name>Cloud€?/name> <version>1.0</version> </app> <app> <id>1</id> <name>Cloud€Traitor?/name> <version>2.0</version> </app> <app> <id>1</id> <name>Cloud€High pressure</name> <version>10.0</version> </app> </apps>
There are many ways to parse xml. pull parsing and SAX parsing are commonly used
pull resolution:
Change the previous part of the code
... private void sendRequestWithOKHttp() { new Thread(() -> { try { ..... Request.Builder().url("http://10.0.2.2:8080/htdos/get_data.xml").build(); ..... parseXmlWithPull(data); ..... }catch (IOException e) { e.printStackTrace(); } }).start(); } ... private void parseXmlWithPull(String data) { try{ XmlPullParserFactory factory=XmlPullParserFactory.newInstance(); XmlPullParser xmlPullParser=factory.newPullParser(); xmlPullParser.setInput(new StringReader(data)); int eventType=xmlPullParser.getEventType();//End is returned after reading the xml_ DOCUMENT //Read the xml start tag and return to START_TAG String id=""; String name=""; String version=""; while (eventType!=XmlPullParser.END_DOCUMENT){ String nodeName=xmlPullParser.getName();//Get node name 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();//nextText() -- it can only be used at start_ Called when tag. When the next element is TEXT, the content of TEXT will be returned; The next element is end_ When tag, that is, the content of this tag is empty, then the empty string is returned; After this method returns, the Parser will stop at END_TAG. } break; } //Finish parsing a node 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(); } } ...
SAX parsing
- Create a new class, inherit DefaultHandler and override the five methods of the parent class
public class ContentHandler extends DefaultHandler { private static final String TAG = "54"; String nodeName; StringBuilder id; StringBuilder name; StringBuilder version; @Override public void endDocument() throws SAXException { super.endDocument(); } @Override public void startDocument() throws SAXException { id=new StringBuilder(); name=new StringBuilder(); version=new StringBuilder(); super.startDocument(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localName, qName, attributes); nodeName=localName; } @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); 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); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); switch (nodeName){ case "id": id.append(ch,start,length); break; case "name": name.append(ch,start,length); break; case "version": version.append(ch,start,length); break; default: break; } } }
Modify code in MainActivity
... private void parseXmlWithAX(String data) { try { SAXParserFactory factory=SAXParserFactory.newInstance(); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new ContentHandler());//Pass in an instance of the written contentHandler xmlReader.parse(new InputSource(new StringReader(data))); } catch (SAXException | ParserConfigurationException | IOException e) { e.printStackTrace(); } }
Parse JOSN
Similarly, create get in htdos_ data. JSON file
[{"id":"5","version":"5.5","name":"Clans of Clans"}, {"id":"6","version":"7.0","name":"Boom Beach"}, {"id":"7","version":"3.5","name":"Clans Royale"}]
Using JSONObject
... private void sendRequestWithOKHttp() { new Thread(() -> { try { ..... Request.Builder().url("http://10.0.2.2:8080/htdos/get_data.json").build(); ..... parseXmlWithPull(data); ..... }catch (IOException e) { e.printStackTrace(); } }).start(); } ... private void parseJsonWithJSONObject(String data) { try{ JSONArray jsonArray=new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject object=jsonArray.getJSONObject(i); String id=object.getString("id"); String name=object.getString("name"); String version=object.getString("version"); Log.d(TAG, "id is "+id); Log.d(TAG, "name is "+name); Log.d(TAG, "version is "+version); } } catch (JSONException e) { e.printStackTrace(); } }
Since we define a JSON array on the server, we first pass the returned data into a JSONArray object. Then loop through the JSONArray. Each element taken out is a JSONObject object, and each JSONObject object will contain data such as id, name and version. Then call the getString () method to take out and print these data.
Using GSON
GSON is an open source library provided by Google. Before using it, you must add the dependency of GSON Library in the project. Under the dependencies closure, add:
implementation 'com.google.code.gson:gson:2.8.6'
The latest version can be queried through the official website:
https://github.com/google/gson
GSON can automatically map a string in JSON format into an object, so there is no need to write code to parse it manually.
If a section of json has the format such as: {"name": "Tom", "age": "20"}
Then you can define a Person class, add the name and age fields, and then simply call the following code to automatically parse JSON data into a Person object:
Gson gson = new Gson(); Person person = gson.fromJson(jsonData,Person.class);
If you need to parse an array, it will be a little troublesome. You need to pass the data type you want to parse into into the fromjason () method with the help of TypeToken:
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());
Encapsulation in development
The codes for sending HTTP requests are basically the same. Generally, during the development process, the general network operations are extracted into a public class, which provides a static method higher than you. When you want to initiate a network request, you only need to simply call this method. It can be as follows:
public class HttpUtil { public static void sendOkHttpRequest(String address, Callback callback){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(address) .build(); client.newCall(request).enqueue(callback); } }
Instead of calling the execute() method before, it is the enqueue() method that was last called. When a request needs to be executed:
1HttpUtil.sendOkHttpRequest("http://www.baidu.com", new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { //Handling exceptions } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { //Get the specific content returned by the server String responseData = response.body().string(); } });
The callback method is used to process the returned data.
Modified according to the article of Hello ood: https://blog.csdn.net/YCF8746/article/details/117201088?spm=1001.2014.3001.5501