OKHttpUtils請求網絡數據工具類

package com.example.ok_http.Util;

import android.os.Handler;
import android.os.Message;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class OkhttpUtile {
    private  MyHandler myHandler = new MyHandler();
    private OKHttpGetListener onOKHttpGetListener;

    //get
    public void get(String url){
        OkHttpClient client = new OkHttpClient();
        //創建請求對象
        Request request = new Request.Builder().url(url).build();
        //創建Call請求隊列,請求都是放到一個隊列裏面
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            //失敗,成功的方法都是在子線程裏面,不能直接更新UI
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = myHandler.obtainMessage();
                message.obj="請求失敗";
                message.what=0;
                myHandler.sendMessage(message);


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = myHandler.obtainMessage();
                String json = response.body().string();
                message.obj = json;
                message.what = 1;
                myHandler.sendMessage(message);

            }
        });

    }

    //使用接口回調,將接口返回
    public  interface OKHttpGetListener{
        void error(String error);
        void success(String json);
    }
    //給外部調用的方法
    public void setOnOKHttpGetListener(OKHttpGetListener onOKHttpGetListener){
        this.onOKHttpGetListener = onOKHttpGetListener;
    }

    //handler
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            int w = msg.what;
            if (w == 0) {
                //請求失敗
                String error = (String) msg.obj;
                onOKHttpGetListener.error(error);
            }
            if (w == 1) {
                String json = (String) msg.obj;
                onOKHttpGetListener.success(json);
            }

        }
    }
}


--------------------------------------MainActivity----------------------------------

package com.example.ok_http;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ok_http.Util.OkhttpUtile;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public String key = "2f41498b35e69877fc56dc96776e5d1f";
    public String url = "http://v.juhe.cn/toutiao/index?type=top&key=" + key;
    private Button get;
    private ListView lv;
    ArrayList<NesBean.ResultBean.DataBean> list = new ArrayList<>();
    private Myadpater md;


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

        initViews();
    }

    //初始化控件
    private void initViews() {
        get = (Button) findViewById(R.id.get);
        get.setOnClickListener(this);
        lv = (ListView) findViewById(R.id.lv);
        md = new Myadpater();
        lv.setAdapter(md);


    }


    @Override
    public void onClick(View view) {
        //創建OKHttpClient對象
        OkhttpUtile ok = new OkhttpUtile();
        ok.get(url);
        
        ok.setOnOKHttpGetListener(new OkhttpUtile.OKHttpGetListener() {
            @Override
            public void error(String error) {
                Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void success(String json) {
                //成功就解析數據
                Gson gson = new Gson();
                NesBean nesBean = gson.fromJson(json, NesBean.class);
                List<NesBean.ResultBean.DataBean> data = nesBean.getResult().getData();
                list.addAll(data);

                md.notifyDataSetChanged();
            }
        });

    }


    //適配器
    class Myadpater extends BaseAdapter {


        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView textView = new TextView(MainActivity.this);
            textView.setText(list.get(i).getTitle());

            return textView;

        }
    }


}
-------------------------------XML文件--------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.ok_http.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="get請求"
        android:id="@+id/get"/>
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv"></ListView>


</LinearLayout>

-----------------------------------------依賴--------------------------------------
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.5.0'
compile 'com.google.code.gson:gson:2.8.2'




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章