Android Road 36 - Android network operation

Guide reading

1. Basic knowledge of network operation
2. Basic knowledge of JSON
3. Request data and analysis from the server

Basic knowledge of network operation

Basic knowledge of JSON

A bracket represents a collection, and a curly bracket represents an object

Request data from server and parse

JSON method

Configuration file Android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hala.view01">

    <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>

        <activity android:name=".DetailActivity"></activity>
    </application>
    <!--Set access to the network, don't forget-->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Homepage layout file activity main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:text="Emilia Clarke"
        android:textSize="28sp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:background="#3f51b5"
        android:paddingRight="15dp"/>
    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"/>
    <ListView
        android:id="@+id/essay_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

Main page java file MainActivity.java

package com.hala.view01;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;


public class MainActivity extends Activity {


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initView();
    }


    public void initView(){
        findViewById(R.id.header).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,DetailActivity.class));
            }
        });
    }

}

Receive data page layout file activity detail

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:layout_marginTop="15dp" />

    <TextView
        android:id="@+id/author"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:gravity="right"
        android:paddingRight="10dp"
        android:layout_marginTop="15dp"/>

    <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>

Receive data page java file DetailActivity.java file

package com.hala.view01;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DetailActivity extends AppCompatActivity {

    private TextView name,author,content;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            essay e=(essay)msg.obj;
            name.setText(e.getTitle());
            author.setText(e.getAuthor());
            content.setText(e.getContent());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        initView();
        initData();
    }

    public void initView(){
        name=(TextView)findViewById(R.id.name);
        author=(TextView)findViewById(R.id.author);
        content=(TextView)findViewById(R.id.content);
    }

    public void initData() {
        /*
        HttpUrlConnection Program steps
        1. Instantiate an object of a Url
        2. Get HttpUrlConnection object
        3. Set request link properties (request method, response time)
        4. Get response code and judge whether the connection is successful
        5. Read input stream and parse
         */

        //Note that the original UI thread should not be used to access the network, but a new thread should be opened up
        new Thread() {
            @Override
            public void run() {
                try {
                    //Step 1: the parameter is the interface you want to access
                    URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");
                    //Step 2: openConnection is of URLConnection type, which is realized by downward modeling
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    //Step 3: capitalize
                    coon.setRequestMethod("GET");
                    //This step is a common response timeout
                    coon.setReadTimeout(6000);

                    //Step 4: this method obtains the response code from the server while connecting to the server
                    if (coon.getResponseCode() == 200) {
                        //Step 5: len is used to record the actual read array length
                        //BIOS is a cache stream that holds the array read
                        InputStream in = coon.getInputStream();
                        byte[] b = new byte[1024 * 512];
                        int len = 0;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = in.read(b)) > -1) {
                            //Parameter 1 array name
                            //Parameter 2, 3 start and end Subscripts
                            baos.write(b, 0, len);
                        }
                        String msg = baos.toString();
                        Log.e("TAG", msg);


                        //***JSON data parsing***
                        JSONObject obj=new JSONObject(msg);
                        //If it is an array, it should be handled as follows
                       // JSONArray array=new JSONArray(msg);
                        int status=obj.getInt("status");
                        String msg2=obj.getString("msg");
                        Log.e("TAG",status+" "+msg2);
                        JSONObject data=obj.getJSONObject("data");
                        String title=data.getString("title");
                        String author=data.getString("author");
                        String content=data.getString("content");
                        Log.e("TAG","title:"+title+" Author:"+author+" Content:"+content);


                        //***Layout the acquired data on the view***
                        /*
                        1. Handler It deals with the relationship between the main thread and the sub thread
                        2. Message It's for information
                        3. Create Handler object as shown in line 24 above - > obtain Message object - > Customize class esay for complex type and pass value (other types can also be used)
                        ->Get the custom type through. obj to Message - > SendMessage and pass it to the method handleMessage() in line 28 above
                        ->Get object or settings view
                         */
                        //Because the data request reopens a sub thread, and Android 4.0 later does not allow to operate the main thread through the sub thread
                        //So here we have to give control to the main thread
                        Message message=handler.obtainMessage();
                        essay e=new essay(title,author,content);
                        message.obj=e;
                        handler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }


}

Custom java file essay.java

package com.hala.view01;

/**
 * Created by air on 2018/1/29.
 */

public class essay {

    private String title;
    private  String author;
    private  String 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;
    }
}

Show results


Click Emilia Clarke

GSON method

How to use Gson

A kind of There's a good chance that you can enter gson and then enter no information. This is com.google.code.gson:gson:2.8.0
If not, write the following icon line in the build.gradle(Module:app) file

Configuration file Android manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hala.view01">

    <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>

        <activity android:name=".DetailActivity"></activity>
    </application>
    <!--Set access to the network, don't forget-->
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

Homepage layout file activity main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:text="Emilia Clarke"
        android:textSize="28sp"
        android:gravity="center"
        android:textColor="#ffffff"
        android:background="#3f51b5"
        android:paddingRight="15dp"/>
    <ImageView
        android:id="@+id/banner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"/>
    <ListView
        android:id="@+id/essay_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>

</LinearLayout>

Main page java file MainActivity.java

package com.hala.view01;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;


public class MainActivity extends Activity {

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };



    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initView();
        initDate();
    }


    public void initView(){
        findViewById(R.id.header).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,DetailActivity.class));
            }
        });
    }

    public void initDate(){
        new Thread(){
            @Override
            public void run() {
                try {
                    URL url=new URL("http://www.imooc.com/api/teacher?type=2");
                    HttpURLConnection conn=(HttpURLConnection)url.openConnection();

                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(6000);

                    if(conn.getResponseCode()==200){
                        InputStream in=conn.getInputStream();
                        byte[] b=new byte[1024*512];
                        int len=0;
                        ByteArrayOutputStream baos=new ByteArrayOutputStream();
                        while((len=in.read(b))>-1){
                            baos.write(b,0,len);
                        }
                        String result=baos.toString();
                        Log.e("TAG",result);
                        /*
                        If you use JSON processing method here, you need to use JSONArray and JSONObject to extract layer by layer. The workload is obvious
                        And this is where GSON comes in. It can facilitate this process
                         */

                        /*
                        GSON
                        1.Parsing common json objects (shown in Detail file)
                        2.Parse json array (this file demonstrates)
                         */

                        //Get data of data type in Json format and give it to string data
                        String data=new JSONObject(result).getString("data");
                        Gson gson=new Gson();
                        //Parameter 1: satisfy the string in the form of json array, which is a collection, so the collection should also be used to receive it
                        //Parameter 2: to convert to what object, TypeToken needs to specify a template, which determines the type of the final conversion
                        //Here, we need to establish the corresponding entity class (in this case, OutLine) according to the type of Json, and the entity class should match with Json
                        //In addition, pay attention to the writing method of this sentence
                       ArrayList<OutLine> outline= gson.fromJson(data,new TypeToken<ArrayList<OutLine>>(){}.getType());
                        for(int i=0;i<outline.size();i++){
                            OutLine o=outline.get(i);
                            Log.e("TAG","id:"+o.getId()+" title:"+o.getName());
                        }

                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}

Receive data page layout file activity detail

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:gravity="center"
        android:layout_marginTop="15dp" />

    <TextView
        android:id="@+id/author"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:gravity="right"
        android:paddingRight="10dp"
        android:layout_marginTop="15dp"/>

    <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>

Receive data page java file DetailActivity.java file

package com.hala.view01;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DetailActivity extends AppCompatActivity {

    private TextView name,author,content;
    private Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            essay e=(essay)msg.obj;
            name.setText(e.getTitle());
            author.setText(e.getAuthor());
            content.setText(e.getContent());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        initView();
        initData();
    }

    public void initView(){
        name=(TextView)findViewById(R.id.name);
        author=(TextView)findViewById(R.id.author);
        content=(TextView)findViewById(R.id.content);
    }

    public void initData() {
        /*
        HttpUrlConnection Program steps
        1. Instantiate an object of a Url
        2. Get HttpUrlConnection object
        3. Set request link properties (request method, response time)
        4. Get response code and judge whether the connection is successful
        5. Read input stream and parse
         */

        //Note that the original UI thread should not be used to access the network, but a new thread should be opened up
        new Thread() {
            @Override
            public void run() {
                try {
                    //Step 1: the parameter is the interface you want to access
                    URL url = new URL("http://www.imooc.com/api/teacher?type=3&cid=1");
                    //Step 2: openConnection is of URLConnection type, which is realized by downward modeling
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    //Step 3: capitalize
                    coon.setRequestMethod("GET");
                    //This step is a common response timeout
                    coon.setReadTimeout(6000);

                    //Step 4: this method obtains the response code from the server while connecting to the server
                    if (coon.getResponseCode() == 200) {
                        //Step 5: len is used to record the actual read array length
                        //BIOS is a cache stream that holds the array read
                        InputStream in = coon.getInputStream();
                        byte[] b = new byte[1024 * 512];
                        int len = 0;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = in.read(b)) > -1) {
                            //Parameter 1 array name
                            //Parameter 2, 3 start and end Subscripts
                            baos.write(b, 0, len);
                        }
                        String msg = baos.toString();
                        Log.e("TAG", msg);


                        /*
                        Parsing common json objects
                        1.Create a Gson object
                         */
                        JSONObject obj=new JSONObject(msg);
                        Gson gson=new Gson();
                        String data=obj.getString("data");
                        //Parameter 1: a string satisfying the json object format (note that the data in json can be converted into strings)
                        //Parameter 2: class object of a class, which is customized here, and its return value is also the class object type
                        essay e=gson.fromJson(data,essay.class);
                        Message message=handler.obtainMessage();
                        message.obj=e;
                        handler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }


}

Custom java file essay.java

package com.hala.view01;

/**
 * Created by air on 2018/1/29.
 */

public class essay {

    private String title;
    private  String author;
    private  String 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;
    }
}

Customization file OutLine

package com.hala.view01;

/**
 * Created by air on 2018/1/30.
 */

public class OutLine {

    private int id;
    private String name;
    private String picSmall;
    private String picBig;
    private String description;
    private String learner;

    public OutLine(int id, String name, String picSmall, String picBig, String description, String learner) {
        this.id = id;
        this.name = name;
        this.picSmall = picSmall;
        this.picBig = picBig;
        this.description = description;
        this.learner = learner;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPicSmall() {
        return picSmall;
    }

    public void setPicSmall(String picSmall) {
        this.picSmall = picSmall;
    }

    public String getPicBig() {
        return picBig;
    }

    public void setPicBig(String picBig) {
        this.picBig = picBig;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getLearner() {
        return learner;
    }

    public void setLearner(String learner) {
        this.learner = learner;
    }
}

Show results


Click Emilia Clarke

Keywords: Android Java JSON xml

Added by rIkLuNd on Sun, 03 May 2020 03:18:50 +0300