OKHttp简介:
OKHttp为square公司的开源项目,已经被google公司添加到开源库中
OKHttp内部依赖okio库,因此使用时也需要导入okio包
OKhttp包及okio包下载地址 http://square.github.io/okhttp/#download,此链接还含有OKhttp的GET和POST请求的使用案例
OKHttp优点:
适合大文件下载与上传
适用于加载图片
OKHttp使用注意:
OKHttp使用时必须在子线程中执行
OKHttp的GET请求:
OkHttpClient client=new OkHttpClient();
String url="";
private String run(String url) throws IOException{
Request request=new Request.Builder()
.url(url)
.build();
Response response=client.newCall(request).execute();
//返回String类型的字符串
return response.body().string();
}
OKHttp的POST请求:
public static final MediaType JSON=MediaType.parse( "application/json; charset=utf-8" );
OkHttpClient client=new OkHttpClient();
private String post(String url,String json) throws IOException{
Request Bodybody=RequestBody.create(JSON,json);
Request request=new Request.Builder()
.url(url)
.post(body)
.build();
Response response=client.newCall(request).execute();
return response.body().string();
}
OKHttp的拓展类okhttp-utils
这个项目为国内大神张鸿洋所创,okhttp-utils地址 https://github.com/hongyangAndroid/okhttputils
okhttp-utils对OKHttp进行了封装,它无需建立子线程执行
okhttp-utils的GET请求:
String url=" ";
OkHttpUtils
.get()
.url(url)
.addParams("username","hyman")
.addParams("password","123")
.build()
.execute(new StringCallback() {
@Override
public void onError(Request request,Exception e) {
}
@Override
public void onResponse(String response) {
}
});
okhttp-utils的POST请求:
OkHttpUtils
.post()
.url(url)
.addParams("username","hyman")
.addParams("password","123")
.build()
.execute(callback);
具体上传的数据还需要视具体情况而定,详情请见 https://github.com/hongyangAndroid/okhttputils
网友评论