使用okHttp、HttpURLConnection 获取网络连接 并使用gson解析数据

 获取网络工具类:

package com.djp.magpietest.json;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpUtil {
    /**
     * 使用HttpURLConnection 获取网络连接
     * @param address
     * @param listener
     */
    public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener!=null){
                        listener.onFisish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null){
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    /**
     * 使用okHttp获取网络连接
     * @param address
     * @param callback
     */
    public static void  sendOkhttpRequest(String address,okhttp3.Callback callback){
        OkHttpClient client  = new OkHttpClient();
        Request request = new Request.Builder().url(address).build();
        client.newCall(request).enqueue(callback);
    }
}

接口:

package com.djp.magpietest.json;

public interface HttpCallbackListener {

    void onFisish(String request);
    void onError(Exception e);
}

实现类:

package com.djp.magpietest.json;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn1;
    private Button btn2;
    List userBeanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = findViewById(R.id.btn1);
        btn2=findViewById(R.id.btn2);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        String address = "http://api.avatardata.cn/TouTiao/Query?key=827f19a56e364adcb32d2db2ea50248d&type=top";
        switch (v.getId()){
            case R.id.btn1:
                 HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
                     @Override
                     public void onFisish(String request) {
                         //得到服务器返回的具体内容
                         Log.d("this",request);
                         parseJsonData(request);
                     }
                     @Override
                     public void onError(Exception e) {
                         //在这里对异常情况处理
                         Log.d("this","系统错误");

                     }
                 });
                break;
            case R.id.btn2:
                HttpUtil.sendOkhttpRequest(address, new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //在这里对异常情况处理
                        Log.d("this","系统错误");
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //得到服务器返回的具体内容
                        String responseData = response.body().string();
                        Log.d("this",responseData);
                        parseJsonData(responseData);
                    }
                });
            default:
                break;
        }
    }

    /**
     * 使用Gson解析数据
     * @param request
     */
    private void parseJsonData(String request) {
        //使用GSON解析多重数据
        newsBean resultBean = new Gson().fromJson(request,newsBean.class);
        userBeanList = resultBean.getResult().getData();
        for (newsBean.Bean1.Bean2 news: userBeanList){
            Log.d("this","title is"+news.getTitle());
            Log.d("this","url"+news.getUrl());
        }
    }
}

bean类:

package com.djp.magpietest.json;

import java.util.List;

public class newsBean {
    private Bean1 result;

    public Bean1 getResult() {
        return result;
    }

    public void setResult(Bean1 result) {
        this.result = result;
    }
    public class Bean1{
        private List data;

        public List getData() {
            return data;
        }

        public void setData(List data) {
            this.data = data;
        }
        class Bean2{
            private String uniquekey;
            private String title;
            private String date;
            private String category;
            private String author_name;
            private String url;
            private String thumbnail_pic_s;

            public String getUrl() {
                return url;
            }

            public void setUrl(String url) {
                this.url = url;
            }

            public String getThumbnail_pic_s() {
                return thumbnail_pic_s;
            }

            public void setThumbnail_pic_s(String thumbnail_pic_s) {
                this.thumbnail_pic_s = thumbnail_pic_s;
            }

            public String getAuthor_name() {
                return author_name;
            }

            public void setAuthor_name(String author_name) {
                this.author_name = author_name;
            }

            public String getUniquekey() {
                return uniquekey;
            }

            public void setUniquekey(String uniquekey) {
                this.uniquekey = uniquekey;
            }

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getCategory() {
                return category;
            }

            public void setCategory(String category) {
                this.category = category;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

        }
    }
}

 

你可能感兴趣的:(Android)