当前位置: 移动技术网 > IT编程>移动开发>Android > Android 网络框架 OKHttp

Android 网络框架 OKHttp

2018年09月05日  | 移动技术网IT编程  | 我要评论

元氏,错缘电影,戚薇和林子君

概述

okhttp是一个网络请求开源项目,android网络请求轻量级框架,支持文件上传与下载,支持https,由移动支付square公司贡献。

依赖

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

get请求

get方式发送同步请求

okhttpclient okhttpclient;
request request;
okhttpclient = new okhttpclient();
request = new request.builder()
        .url("http://www.baidu.com")//请求接口,如果需要传参拼接到接口后面,如www.baidu.com?name=zhangsan&sex=18
        .build();
final call call = okhttpclient.newcall(request);
new thread(new runnable() {
    @override
    public void run() {
        try {
            response response = call.execute();//得到response 对象
            if(response.issuccessful()){//判断是否响应
                log.d("response ","响应码"+response.code());//返回http协议的响应码
                log.d("response ","返回内容"+response.body().string());
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
});

get方式发送异步请求

okhttpclient okhttpclient;
request request;
okhttpclient = new okhttpclient();
request = new request.builder()
        .url("http://www.baidu.com")//请求接口。如果需要传参拼接到接口后面,如www.baidu.com?name=zhangsan&sex=18
        .build();
final call call = okhttpclient.newcall(request);
call.enqueue(new callback() {
     @override
     public void onfailure(call call, ioexception e) {

     }

     @override
     public void onresponse(call call, response response) throws ioexception {
            if(response.issuccessful()){//判断是否响应
                log.d("response ","响应码"+response.code());//返回http协议的响应码
                log.d("response ","返回内容"+response.body().string());
            }
     }
 });

post请求

formbody传递键值对参数

formbody body = new formbody.builder() //创建信息主体
        .add("name", name)
        .add("sex", department)
        .add("possword", post)
        .add("data", formatter.format(getdata()))
        .build();

requestbody传递json或file对象

//传递json对象
mediatype json = mediatype.parse("application/json; charset=utf-8");//指定数据类型为json对象,
string jsonstr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据.
requestbody body = requestbody.create(json, josnstr);

//传递file对象
mediatype filetype = mediatype.parse("file/*");//指定数据类型为file对象,
file file = new file(path);//file对象
requestbody body = requestbody.create(filetype , file );

multipartbody传递键值对对象和 file对象

multipartbody multipartbody =new multipartbody.builder()
        .settype(multipartbody.form)
        .addformdatapart("groupid",""+id)//添加键值对参数
        .addformdatapart("file",file.getname(),requestbody.create(mediatype.parse("file/*"), file))//添加文件
        .build();

post同步/异步请求

//formbody传递数据,post同步请求
okhttpclient okhttpclient;
okhttpclient = new okhttpclient();
formbody body = new formbody.builder() //创建信息主体
        .add("name", name)
        .add("sex", department)
        .add("possword", post)
        .add("data", formatter.format(getdata()))
        .build();
request requset = new request.builder()
        .url("url")
        .post(body)
        .build();
final call call = okhttpclient.newcall(requset);
new thread(new runnable() {
    @override
    public void run() {
        try {
            response response = call3.execute();//得到response 对象
            if(response.issuccessful()){//判断是否响应
                log.d("response ","响应码"+response.code());//返回http协议的响应码
                log.d("response ","返回内容"+response.body().string());
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
});

//requestbody()传递数据,post异步请求
okhttpclient okhttpclient;
okhttpclient = new okhttpclient();
mediatype json = mediatype.parse("application/json; charset=utf-8");//数据类型为json格式,
string jsonstr = "{\"username\":\"lisi\",\"nickname\":\"李四\"}";//json数据.
requestbody body = requestbody.create(json, jsonstr);
request request = new request.builder()
        .url("http://www.baidu.com")
        .post(body)
        .build();
final call call = okhttpclient.newcall(requset);
call.enqueue(new callback() {
    @override
    public void onfailure(call call, ioexception e) {

    }

    @override
    public void onresponse(call call, response response) throws ioexception {
        if(response.issuccessful()){//判断是否响应
            log.d("response ","响应码"+response.code());//返回http协议的响应码
            log.d("response ","返回内容"+response.body().string());
        }
    }
});

常规请求概述

通过上述代码,get或post请求需要实例化okhttpclient对象,用request创建请求和response发送请求,以及call调度器接收返回内容。

call对象有两种模式,call.excute()同步模式,call.enqueue()异步模式。

同步是在主线程操作,所以需要开启子线程操作。异步是callback回调回来的response,是在子线程操作,但是回调的onfailure()和onresponse()依然在子线程中。

respinse.body() 也是在子线程,需要接收到内容,才能调用主线程操作。

注意response.body()只能调用一次,因为是输出流的读操作,而读写操作只接收一次,第二次会返回null。

设置网络超时

okhttpclient okhttpclient = new okhttpclient.builder()
    .connecttimeout(10, timeunit.seconds)//设置超时时间
    .readtimeout(10, timeunit.seconds)//设置读取超时时间
    .writetimeout(10, timeunit.seconds);//设置写入超时时间

 okhttp的拦截器

 转载 — 关于okhttp的拦截器

okhttp下载文件

 转载 — okhttp下载文件实例

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网