1. Instantiating URL objects
The first step is to instantiate a URL object and pass in the address whose parameter is the requested data.
URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");
2. Get the HttpURLConnection object
Calling the open Connection method of the URL object returns a URLConnection object, and the URLConnection class is the parent of the HttpURLConnection class, which can be coerced into the HttpURLConnection object we need.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3. Setting Request Connection Properties
The attributes of the connection can be set by the HTTP URLConnection object acquired in the second step, such as setRequestMethod setting connection type "GET" or "POST", setReadTimeout setting read timeout, and so on.
conn.setRequestMethod("GET"); conn.setReadTimeout(6000);
4. Get the response code
The response code is used to confirm whether the connection result is connected or not. If the return value is 200, the connection is successful.
conn.getResponesCode();
5. Read and parse input stream
Through the HttpURLConnection object, an input stream can be obtained, and the content of the input stream can be read locally and parsed in an appropriate way.
It can be parsed directly with JSONObject, or with a third-party framework, gson is recommended.
if (conn.getResponesCode() == 200) { InputStream in = conn.getInputStream(); byte[] b = new byte[1024 * 512]; int len = 0; //Create a cache stream to save the read byte array ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = in.read(b)) > -1) { baos.write(b, 0, len); } String msg = baos.toString(); //Parsing data JSONObject obj = new JSONObject(msg); JSONObject data = obj.getJSONObject("data"); String title = data.getString("title"); String author = data.getString("author"); String content = data.getString("content"); }
A brief introduction to gson parsing data:
(1) gson parses ordinary json objects: the use of gson depends on JSONObject, through the getString method of JSONObject object, obtains the corresponding data in the form of strings, and then parses it into specified classes.
String data = obj.getString("data");//Objectj is a JSONObject obj ect GSON gson = new GSON(); Essay e = gson.fromJson(data, Essay.class);//The first parameter is a string in the form of a json object, and the second parameter is a custom class. If you need to parse the json object into any type, you pass in the corresponding class.
(2) gson parses array data:
The steps of parsing data in array form are basically the same as those of ordinary json objects. The difference is that the first parameter of fromJson method is a string satisfying json array form, the second parameter is a Type object, and the Type object needs to be obtained by the getType method of the TypeToken object.
Get the Type object: new TypeToken
String data = new JSONObject(result).getString("data");//result is an unresolved json string GSON gson = new GSON(); Type listType = new TypeToken<ArrayList<Essay>>(){}.getType(); ArrayList<Essay> e = gson.fromJson(data, listType);
6. Pass data back to the main thread
Because network operations cannot be performed in the main thread and sub-threads are not allowed to operate on the UI, it is necessary to pass the parsed data back to the main thread.
Using Handler and Message to communicate between threads, see the complete example below.
7. Complete cases
Layout xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.studying.network.DetailActivity"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:gravity="center" android:textSize="24sp" /> <TextView android:id="@+id/author" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:gravity="right" android:paddingRight="10dp" android:textSize="20sp" /> <TextView android:id="@+id/content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="8dp" android:layout_marginTop="15dp" android:layout_weight="1" android:lineSpacingMultiplier="1.5" android:textSize="20sp" /> </LinearLayout>
Activity:
public class DetailActivity extends Activity { private TextView titleView, authorView, contentView; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Essay essay = (Essay) msg.obj; titleView.setText(essay.getTitle()); authorView.setText(essay.getAuthor()); contentView.setText(essay.getContent()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); initView(); initData(); } public void initView() { titleView = (TextView) findViewById(R.id.title); authorView = (TextView) findViewById(R.id.author); contentView = (TextView) findViewById(R.id.content); } public void initData() { //Network operations cannot be performed in the main thread new Thread(){ @Override public void run() { try { URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(6000); //Get the response code and connect to the network at the same time if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); byte[] b = new byte[512 * 1024]; int len = 0; //Transfer the contents of the input stream to the byte array stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = in.read(b)) > -1){ baos.write(b, 0, len); } String result = baos.toString(); //Parsing data JSONObject obj = new JSONObject(result); JSONObject data = obj.getJSONObject("data"); String title = data.getString("title"); String author = data.getString("author"); String content = data.getString("content"); //Pass data back to the main thread through Message Message message = handler.obtainMessage(); Essay essay = new Essay(title, author, content);//Essay is a custom class for passing multiple values message.obj = essay; handler.sendMessage(message);//Calling this method triggers the handleMessage method in the Handler object in the main thread conn.disconnect(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }.start(); } }
Essay:
public class Essay { private String title, author, content; public Essay(String title, String author, String content) { this.title = title; this.author = author; this.content = content; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }