OKHTTP网络请求的GET方法

首先要依赖两个包  在app的build.gradle
compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.5.0'


 
  
package licancan.com.okhttp;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

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

import licancan.com.okhttp.adapter.MyAdapter;
import licancan.com.okhttp.bean.Bean;
import view.xlistview.XListView;

public class MainActivity extends AppCompatActivity {

    private XListView xlv_list;
    private MyAdapter adapter;

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

        initView();
        initData();
    }


    /**
     * 初始化
     */
    private void initView() {
        xlv_list = (XListView) findViewById(R.id.xlv_list);
    }

    /**
     * GET请求数据的方法
     */
    private void initData() {
        //网络地址
        String url="http://api.tianapi.com/huabian/?key=5baef83129decfa305bbc140b085d8a1&num=10";
        //创建OKHttp对象
        OkHttpClient okHttpCient=new OkHttpClient();
        //创建一个Request
        Request request=new Request.Builder().url(url).build();
        //创建一个call对象
        Call call=okHttpCient.newCall(request);
        //将请求添加到调度中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                if(response.isSuccessful())
                {
                    //获取json串
                    final String message=response.body().string();
                    //打印json
                    System.out.println("json============="+message);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //在子线程中解析json
                            getJson(message);
                        }
                    });
                }
            }
        });
    }

    /**
     * 解析json串的方法
     */
    private void getJson(String result) {
        Gson gson=new Gson();
        Bean bean = gson.fromJson(result, Bean.class);
        List list = bean.getNewslist();
        for (Bean.NewslistBean b : list) {
            System.out.println("bean========"+b.getTitle()+"  "+b.getCtime()+" "+b.getPicUrl());
        }

        //创建适配器
        if(adapter==null)
        {
            adapter = new MyAdapter(this,list);
            xlv_list.setAdapter(adapter);
        }
        else{
            adapter.notifyDataSetChanged();
        }
    }


}

你可能感兴趣的:(OKHTTP网络请求的GET方法)