okhttp的两种简易请求


在我们现阶段,okhttp请求框架还是非常流行的。以下是我对get和post两种请求框架的简易实现。



1.okhttp请求框架的get请求



在写代码之前我们应该添加okhtpp的依赖:

compile 'com.squareup.okhttp3:okhttp:3.2.0'

在代码中书写一个方法或者书写一个工具类

先创建okhttp对象

OkHttpClient  client=new OkHttpClient();


在创建一个Request对象

Request request = new Request.Builder().url(url).build();


默认的请求方式是get

通过Okhttp的对象生成call对象

Call call=client.newCall(request);

通过call来得到结果的返回

call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

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

 2.书写okhtttp请求中的post请求

//创建OkHttpClient
OkHttpClient mOkHttpClient = new OkHttpClient();
//封装请求参数
FormBody formBody=new FormBody.Builder().add("activity_id",4+"").add("time_id",2927+"").add("child_num",1+"").add("contact","xiallin")
        .add("mobile","15718812709").add("remark",1+"").build();
得到Requrest对象
Request build = new Request.Builder().url(url).post(formBody).build();
//得到Call对象
Call call = client.newCall(build);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String string = response.body().string();
        Message ms=new Message();
        ms.obj=string;
        ms.what=1;
        handler.sendMessage(ms);
    }
});






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值