okHttp的GET方法(异步)

本文介绍了如何使用OkHttp进行异步GET请求,通过示例代码展示从基础到封装的步骤。强调了同步(execute())在主线程中执行,而异步(enqueue())在后台线程。示例中选择了enqueue()进行讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在我们来写一下okHttp的get用法,其实okHttp和HTTPClient、HttpUrlConnection的用法差不多,就和大家写写从最基础的OKHttp的简单get的使用,再到它的封装。它有两种方法:同步和异步,同步(execute())是在主线程中,异步(enqueue())相反。在这里我用的是异步。不多说直接看代码吧:

首先我们要在:

build.gradle中添加依赖:

compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.5.0'

在MainActivity中:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.example.okhttptext.adapter.MyAdapter;
import com.example.okhttptext.bean.News;
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 view.xlistview.XListView;

public class MainActivity extends AppCompatActivity {
    private XListView xlistView;
    private List<News.NewslistBean> list;
    private  News news = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
	//获取控件
        xlistView= (XListView) findViewById(R.id.xlistView);
        //创建OKhttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
        //创建一个request
        Request request=new Request.Builder()
                .url("http://api.tianapi.com/huabian/?key=85adeb9beb2e10492d23168cbe65573c&num=10")
                .build();
        /**
         * 以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url,
         * 当然你可以通过Request.Builder设置更多的参数比如:header、method等。
         * 然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,
         * 既然是任务,就会有execute()和cancel()等方法。
         */
        Call call=okHttpClient.newCall(request);
        //请求加入调度  异步任务
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }
            @Override
            public void onResponse(final Response response) throws IOException {
                if (response.isSuccessful()) {
                    //获取json串res
                    final String res = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //解析
                            Gson gson=new Gson();
                                try {
                                    news = gson.fromJson(res, News.class);
                                    list = news.getNewslist();
                                    MyAdapter adapter=new MyAdapter(MainActivity.this,list);
                                    xlistView.setAdapter(adapter);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值