Android http请求、xml解析、json解析

Android http请求、xml解析、json解析

实验结果

在这里插入图片描述

D/kwwl: response.code()==200
D/kwwl: response.message()==OK
D/kwwl: res == <apps>
        <app>
            <id>1</id>
            <name>Google Maps</name>
            <version>1.0</version>
        </app>
        <app>
            <id>2</id>
            <name>Chrome</name>
            <version>2.1</version>
        </app>
        <app>
            <id>3</id>
            <name>Google Play</name>
            <version>2.3</version>
        </app>
    </apps>

I/System.out: pull方法解析xml: 
E/MainActivity: id is 1
E/MainActivity: name is Google Maps
E/MainActivity: version is 1.0
E/MainActivity: id is 2
E/MainActivity: name is Chrome
E/MainActivity: version is 2.1
E/MainActivity: id is 3
E/MainActivity: name is Google Play
E/MainActivity: version is 2.3
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa3d4720
I/System.out: sax方法解析xml: 
I/System.out: 开始解析的节点为localName==nodeName== apps
I/System.out: 开始解析的节点为localName==nodeName== app
I/System.out: 开始解析的节点为localName==nodeName== id
I/System.out: 解析完此节点为localName:id
I/System.out: 此时的nodeName为: id
I/System.out: 开始解析的节点为localName==nodeName== name
I/System.out: 解析完此节点为localName:name
I/System.out: 此时的nodeName为: name
I/System.out: 开始解析的节点为localName==nodeName== version
I/System.out: 解析完此节点为localName:version
I/System.out: 此时的nodeName为: version
I/System.out: 解析完此节点为localName:app
I/System.out: 此时的nodeName为: version
E/ContentHandler: id is 1
E/ContentHandler: name is Google Maps
E/ContentHandler: version is 1.0
I/System.out: 开始解析的节点为localName==nodeName== app
I/System.out: 开始解析的节点为localName==nodeName== id
I/System.out: 解析完此节点为localName:id
I/System.out: 此时的nodeName为: id
I/System.out: 开始解析的节点为localName==nodeName== name
I/System.out: 解析完此节点为localName:name
I/System.out: 此时的nodeName为: name
I/System.out: 开始解析的节点为localName==nodeName== version
I/System.out: 解析完此节点为localName:version
I/System.out: 此时的nodeName为: version
I/System.out: 解析完此节点为localName:app
I/System.out: 此时的nodeName为: version
E/ContentHandler: id is 2
E/ContentHandler: name is Chrome
E/ContentHandler: version is 2.1
I/System.out: 开始解析的节点为localName==nodeName== app
I/System.out: 开始解析的节点为localName==nodeName== id
I/System.out: 解析完此节点为localName:id
I/System.out: 此时的nodeName为: id
I/System.out: 开始解析的节点为localName==nodeName== name
I/System.out: 解析完此节点为localName:name
I/System.out: 此时的nodeName为: name
I/System.out: 开始解析的节点为localName==nodeName== version
I/System.out: 解析完此节点为localName:version
I/System.out: 此时的nodeName为: version
I/System.out: 解析完此节点为localName:app
I/System.out: 此时的nodeName为: version
E/ContentHandler: id is 3
E/ContentHandler: name is Google Play
E/ContentHandler: version is 2.3
I/System.out: 解析完此节点为localName:apps
I/System.out: 此时的nodeName为: version

D/kwwl: response.code()==200
D/kwwl: response.message()==OK
D/kwwl: res == [{"id":"5","version":"5.5","name":"Clash of Clans"},
     {"id":"6","version":"7.0","name":"Boom Beach"},
     {"id":"7","version":"3.5","name":"Clash Royale"}]

I/System.out: jsonObject方法解析json: 
E/jsonObject: id is 5
E/jsonObject: name is Clash of Clans
E/jsonObject: version is 5.5
E/jsonObject: id is 6
E/jsonObject: name is Boom Beach
E/jsonObject: version is 7.0
E/jsonObject: id is 7
E/jsonObject: name is Clash Royale
E/jsonObject: version is 3.5
I/System.out: GSON方法解析json: 
E/Gson: id is 5
E/Gson: name is Clash of Clans
E/Gson: version is 5.5
E/Gson: id is 6
E/Gson: name is Boom Beach
E/Gson: version is 7.0
E/Gson: id is 7
E/Gson: name is Clash Royale
E/Gson: version is 3.5

MainActivity

package com.example.networktest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

import org.json.JSONArray;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    TextView responseText;
    EditText editText;
    String responseData;

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

        Button sendRequest = (Button) findViewById(R.id.send_request);
        Button sendRequest_ok = (Button) findViewById(R.id.send_request_ok);
        Button get_xml_Pull = (Button) findViewById(R.id.get_xml_Pull);
        Button get_xml_SAX  = (Button) findViewById(R.id.get_xml_SAX);
        Button get_json_jsonObject = (Button) findViewById(R.id.get_json_jsonObject);
        Button get_json_jsonGSON = (Button) findViewById(R.id.get_json_GSON);
        editText = (EditText) findViewById(R.id.edit_text);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
        sendRequest_ok.setOnClickListener(this);
        get_xml_Pull.setOnClickListener(this);
        get_xml_SAX.setOnClickListener(this);
        get_json_jsonObject.setOnClickListener(this);
        get_json_jsonGSON.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.send_request:{
                sendRequestWithHttpURLConnection();
                break;
            }
            case R.id.send_request_ok:{
                sendRequestWithOKHttp();
                break;
            }
            case R.id.get_xml_Pull:{
                System.out.println("pull方法解析xml: ");
                parseXMLWithPull(responseData);
                break;
            }
            case R.id.get_xml_SAX:{
                System.out.println("sax方法解析xml: ");
                parseXMLWithSAX(responseData);
                break;
            }
            case R.id.get_json_jsonObject:{
                System.out.println("jsonObject方法解析json: ");
                parseJSONWithJSONOBJECT(responseData);
                break;
            }
            case R.id.get_json_GSON:{
                System.out.println("GSON方法解析json: ");
                parseJSONWithGSON(responseData);
                break;
            }
            default:break;
        }
    }

    private void sendRequestWithHttpURLConnection(){
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            //开启一个子线程,然后在子线程中发出一条Http请求,
            //接着利用bufferedreader对服务器返回的流进行读取、显示
            @Override
            public void run() {
                HttpURLConnection httpURLConnection = null;
                BufferedReader reader = null;
                try{
                    String string_url = editText.getText().toString();
                    URL url = new URL(string_url);
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(8000);
                    httpURLConnection.setReadTimeout(8000);
                    InputStream in = httpURLConnection.getInputStream();
                    //下面对获取的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder reponse = new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null){
                        reponse.append(line);
                    }
                    showResponse(reponse.toString());
                }catch(Exception e){
                    e.printStackTrace();
                }
                finally {
                    if(reader!=null){
                        try{
                            reader.close();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if(httpURLConnection!=null){
                        httpURLConnection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void sendRequestWithOKHttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String string_url = editText.getText().toString();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(string_url)
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        showToastResponse("response.isSuccessful() == true 打开成功");
                        Log.d("kwwl", "response.code()==" + response.code());
                        Log.d("kwwl", "response.message()==" + response.message());
                        showToastResponse("response.cod  e()==" + response.code());
                        showToastResponse("response.message()==" + response.message());
                        responseData = response.body().string();
                        showResponse(responseData);
                        Log.d("kwwl","res == " + responseData);
                    } else {
                        showToastResponse("response.isSuccessful() == false 打开失败");
                        showToastResponse("response.code()==" + response.code());
                        showToastResponse("response.message()==" + response.message());
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            /*安卓不允许在子线程中进行UI操作,
            所以调用runOnUIThread将线程切换到主线程然后再更新UI元素*/
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }

    private void showToastResponse(final String ToastText){
        //打印toast
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, ToastText, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void parseXMLWithPull(String xmlData){
        try{
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            /*获取一个XmlPullParserFactory实例,借助这个实例得到xmlPullParser对象*/
            XmlPullParser xmlPullParser = factory.newPullParser();

            xmlPullParser.setInput(new StringReader(xmlData));
            /*调用setPut方法将xml的数据传入*/
            int eventType = xmlPullParser.getEventType();
            /*getEventType得到当前解析事件*/
            String id = "";
            String name = "";
            String version = "";
            while(eventType != XmlPullParser.END_DOCUMENT){
                /*如果evenType不等于END_DOCUMENT则说明解析工作没完成,继续循环*/
                String nodeName = xmlPullParser.getName();
                /*得到当前节点的名字*/
                switch(eventType){
                    //开始解析某个节点
                    case XmlPullParser.START_TAG:{
                        if("id".equals(nodeName)){
                            id = xmlPullParser.nextText();
                            /*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.e("MainActivity","id is " + id);
                            Log.e("MainActivity","name is " + name);
                            Log.e("MainActivity","version is " + version);
                        }
                        break;
                    }
                    default:break;
                }
                eventType = xmlPullParser.next();
                /*调用next方法获取下一个解析事件*/
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void parseXMLWithSAX(String xmlData){
        try{
            //创建一个factory对象
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            //获取XMLReader对象
            XMLReader xmlReader = saxParserFactory.newSAXParser().getXMLReader();
            //新建一个contentHandler实例
            ContentHandler contentHandler = new ContentHandler();
            //将contentHandler实例设置到xmlreader中
            xmlReader.setContentHandler(contentHandler);
            //开始执行解析
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private void parseJSONWithJSONOBJECT(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.e("jsonObject","id is " + id);
                Log.e("jsonObject","name is " + name);
                Log.e("jsonObject","version is " + version);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    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.e("Gson","id is " + app.getId());
            Log.e("Gson","name is " + app.getName());
            Log.e("Gson","version is " + app.getVersion());
        }
    }
}


ContentHandler类

package com.example.networktest;

import android.util.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ContentHandler extends DefaultHandler {
    /*SAX 解析需要使用contentHandler的对象与方法*/

    private String nodeName;
    private StringBuilder id;
    private StringBuilder name;
    private StringBuilder version;

    @Override
    public void startDocument() throws SAXException {
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
        //初始化三个builder
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //开始解析某个节点时,调用startElement()
        //记录当前节点名称:localname存放的是当前节点的名称,这里把他取出来。
        nodeName = localName;
        System.out.println("开始解析的节点为localName==nodeName== " + nodeName);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //解析具体节点内容时会调用characters()
        //将解析出来的内容添加到builder中
        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 {
        /*解析完节点内部内容之后调用endElement()*/
        System.out.println("解析完此节点为localName:" + localName + "\n此时的nodeName为: " + nodeName);
        if("app".equals(localName)){
            //必须使用localname,不能用nodename
            Log.e("ContentHandler","id is " + id.toString().trim());
            /*trim()删除字符串头尾的空白符*/
            Log.e("ContentHandler","name is " + name.toString().trim());
            Log.e("ContentHandler","version is " + version.toString().trim());
            /*清空三个builder的内容*/
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }
}

APP类

package com.example.networktest;

public class App {
    /*验证使用GSON*/
    private String id;
    private String name;
    private String version;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getVersion() {
        return version;
    }

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

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

    public void setVersion(String version) {
        this.version = version;
    }
}

其余配置

Manifest
打开权限
在这里插入图片描述

gradle
添加依赖
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值