okttp3及多种网络数据解析

来源:互联网 发布:python小甲鱼视频 编辑:程序博客网 时间:2024/05/16 16:00

转载请注明出处:http://blog.csdn.net/mr_leixiansheng/article/details/77507547


内容:主要包含okttp3 的使用以及Pull数据解析、Json数据解析、GSON数据解析

步骤简介:

一、okttp3

1)引入第三方依赖 : compile 'com.squareup.okhttp3:okhttp:3.4.1'

2)在线程中实例化OkHttpClient对象

3)获取数据

 Request request = new Request.Builder().url("http://www.baidu.com")                            .build();  Response response = client.newCall(request).execute();  String responseData = response.body().string();
4)数据处理

二、JSON数据解析
1)实例化JSONArray 对象将获取的json数据传入
2)遍历JSONArray 将数据一条条取出
JSONObject jsonObject = jsonArray.getJSONObject(i);String id = jsonObject.getString("id");String name = jsonObject.getString("name");String version = jsonObject.getString("version");

三、GSON解析

1)引入第三方依赖:compile 'com.google.code.gson:gson:2.7'

2)构建数据类(设置好set get)

3)实例化GSON、取出数据,进行遍历


代码如下:

数据类

package com.leixiansheng.test2;/** * Created by Leixiansheng on 2017/8/23. */public class App {    private String id;    private String name;    private String version;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getVersion() {        return version;    }    public void setVersion(String version) {        this.version = version;    }}
主程序

package com.leixiansheng.test2;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ScrollView;import android.widget.TextView;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import org.xmlpull.v1.XmlPullParserFactory;import java.io.IOException;import java.io.StringReader;import java.util.HashMap;import java.util.List;import java.util.Map;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;/** * Created by Leixiansheng on 2017/8/22. * Okttp3 需要引入三方依赖: compile 'com.squareup.okhttp3:okhttp:3.4.1' * GSON解析 需要引入三方依赖:compile 'com.google.code.gson:gson:2.7' */public class Okhttp3Acitvity extends AppCompatActivity implements View.OnClickListener{    private final static String TAG = "Okhttp3Acitvity";    private Button btnGet;    private Button btnPost;    private TextView textView;    private String responseData = "";    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            switch (msg.what) {                case 1:                    textView.setText(responseData);            }        }    };    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_okhttp3);        initView();        setOnclick();    }    private void setOnclick() {        btnPost.setOnClickListener(this);        btnGet.setOnClickListener(this);    }    private void initView() {        btnGet = (Button) findViewById(R.id.get_btn);        btnPost = (Button) findViewById(R.id.post_btn);        textView = (TextView) findViewById(R.id.text_view);    }    @Override    public void onClick(View view) {        switch (view.getId()) {            case R.id.get_btn:                getRequest();                break;            case R.id.post_btn:                break;        }    }    public void getRequest() {       //网络请求、耗时操作用线程        new Thread(new Runnable() {            @Override            public void run() {                try {                    OkHttpClient client = new OkHttpClient();                    /**                     * 网页解析                     */                 /*   Request request = new Request.Builder().url("http://www.baidu.com")                            .build();                    Response response = client.newCall(request).execute();                    responseData = response.body().string();                    parseJson(responseData);                    handler.sendEmptyMessage(1);*/                    /**                     * Pull解析  (xml)                     */                    //指定访问本机地址(虚拟机上)                   /* Request request = new Request.Builder().url("http://10.0.2.2/get_data.xml")                            .build();                    Response response = client.newCall(request).execute();                    responseData = response.body().string();                    parseXML(responseData);                    handler.sendEmptyMessage(1);*/                    /**                     * JSON解析                     */                   //指定访问本机地址(虚拟机上)                   /* Request request = new Request.Builder().url("http://10.0.2.2/get_data.json")                            .build();                    Response response = client.newCall(request).execute();                    responseData = response.body().string();                    parseJson(responseData);                    handler.sendEmptyMessage(1);*/                    /**                     * GSON解析(比JSON更好用)                     */                    //指定访问本机地址(虚拟机上)                    Request request = new Request.Builder().url("http://10.0.2.2/get_data.json")                            .build();                    Response response = client.newCall(request).execute();                    responseData = response.body().string();                    parseJsonWithGSON(responseData);                    handler.sendEmptyMessage(1);                } catch (Exception e) {                    e.printStackTrace();                }            }        }).start();    }    private void parseJsonWithGSON(String jsonData) {        Gson gson = new Gson();        //单条数据//        App app = gson.fromJson(jsonData, App.class);        //多条数据        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {        }.getType());        for (App app : appList) {            Log.d(TAG, "id:" + app.getId());            Log.d(TAG, "name:" + app.getName());            Log.d(TAG, "version:" + app.getVersion());        }    }    private void parseXML(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 = xmlPullParser.nextText();                        } else if ("name".equals(nodeName)) {                            name = xmlPullParser.nextText();                        } else if ("version".equals(nodeName)) {                            version = xmlPullParser.nextText();                        }                        break;                    //完成解析某个节点                    case XmlPullParser.END_TAG:                        if ("app".equals(nodeName)) {                            Log.d(TAG, "id:" + id);                            Log.d(TAG, "name:" + name);                            Log.d(TAG, "version:" + version);                        }                        break;                }                eventType = xmlPullParser.next();            }        } catch (XmlPullParserException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    private void parseJson(String jsonData) {        Log.d("MainActivity", 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(TAG, "id:" + id);                Log.d(TAG, "name:" + name);                Log.d(TAG, "version:" + version);            }        } catch (JSONException e) {            e.printStackTrace();        }    }}