用过Volley的人应该感觉封装已经相当不错了,但有些人说这个Okhttp 的效率高,作为一名技术屌丝,真心感觉不出来。
不过简单的使用OkHttp后老是感觉访问完数据后,这个访问的线程会经过一段时间才会关闭,错以为访问失败。使用这个OkHttp给我最大的感受就是,如果有Volley我绝不会用这个OkHttp,比如访问一张图片的时候,这个OkHttp貌似只能帮你请求到这个bytes数据就Ok了,而Volley会返回成Bitmap,并且这个还可以方便的改变图片的尺寸,和大小,还可以进行设置缓存什么的以免OOM,但这个OkHttp就无能为力了,或许是我还不会全部的使用,只是简单的下载文件罢了。
我是采用三种常见的形式进行举例的:读取文本内容,下载文件,简单的Post 请求。
既然是第三方,所以必不可少的就是导包了:在Eclipce中需要导两个包:okhttp-3.4.1.jar 和 okio-1.8.0.jar
对于请求又分为两种,一个就是填参就行,另一个就是直接匿名类直接new 就行,这个我是用请求文本和下载文件这两种进行区分。
请求文本
/**
* 读取文本内容
*/
private static void accessTxt() {
// TODO Auto-generated method stub
OkHttpClient okClient = new OkHttpClient();
Request request = new Request.Builder().url("http://localhost:8081/LoginTest/data.txt").build();
try {
Response response = okClient.newCall(request).execute();
if (response.isSuccessful()) {
String msg = response.body().string();
System.out.println(msg);
} else {
System.out.println("连接服务器失败返回错误代码" + response.code());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
请求文件
/**
* 下载文件
*/
private static void accessImageAndFile() {
// TODO Auto-generated method stub
OkHttpClient okClient = new OkHttpClient();
Request request = new Request.Builder().url("http://localhost:8081/LoginTest/image.jpg").build();
try {
okClient.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
// TODO Auto-generated method stub
byte[] buffer = arg1.body().bytes();
OutputStream oStream = new FileOutputStream("newImage.jpg");
oStream.write(buffer);
oStream.close();
}
@Override
public void onFailure(Call arg0, IOException arg1) {
// TODO Auto-generated method stub
System.out.println("获取服务器数据失败");
}
});
} catch (Exception e) {
// TODO: handle exception
System.out.println(e);
}
}
Post请求
/**
* post请求
*/
private static void postAccess() {
// TODO Auto-generated method stub
OkHttpClient cHttpClient = new OkHttpClient();
// 创建表单构建器
FormBody.Builder builder = new FormBody.Builder();
builder.add("userName", "hejingzhou");
builder.add("userPassword", "1230");
// 创建请求体,通过构建器请求体
RequestBody body = builder.build();
Request request = new Request.Builder().url("http://localhost:8081/LoginTest/hello").post(body).build();
try {
Response response = cHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
System.out.println("服务器返回代码: " + response.code());
System.out.println(response.body().string());
} else {
int backCode = response.code();
System.out.println(backCode);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
关于body 中常用的返回数据类型方法:
response.body().toString();
response.body().bytes();
response.body().byteStream();
response.body().charStream();
response.body().contentLength();
response.body().contentType();
response.body().source();
源码:http://download.csdn.net/detail/csdnhejingzhou/9608538