一、OkHttp简介
OkHttp是一款优秀的HTTP框架,它支持get请求和post请求,支持基于Http的文件上传和下载,支持加载图片,支持下载文件透明的GZIP压缩,支持响应缓存避免重复的网络请求,支持使用连接池来降低响应延迟问题。
OkHttp官网地址:http://square.github.io/okhttp/
OkHttp GitHub地址:https://github.com/square/okhttp
Android Studio中OkHttp的配置方法:
在GRADLE中添加
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.11.0'
注意:okhttp内部依赖okio,所以同时还需要导入okio:
二、OkHttp的基本使用
1、Requests
每一个HTTP请求中都应该包含一个URL,一个GET或POST方法以及Header或其他参数,当然还可以含特定内容类型的数据流。
public final class Request {
private final HttpUrl url;
private final String method;
private final Headers headers;
private final RequestBody body;
private final Object tag;
... ...
}
2、Responses
响应则包含一个回复代码(200代表成功,404代表未找到),Header和定制可选的body。
public final class Response implements Closeable {
private final Request request;
private final Protocol protocol;
private final int code;
private final String message;
private final Handshake handshake;
private final Headers headers;
private final ResponseBody body;
private final Response networkResponse;
private final Response cacheResponse;
private final Response priorResponse;
private final long sentRequestAtMillis;
private final long receivedResponseAtMillis;
... ...
}
在日常开发中最常用到的网络请求就是GET和POST两种请求方式。
三、OkHttp的GET网络请求方法
1、异步get
/**
* 异步get,直接调用
*/
private final String IMAGE_URL = "...";
private OkHttpClient client;
private void asyncGet() {
client = new OkHttpClient();
final Request request = new Request.Builder().get()
.url(IMAGE_URL)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//......
}
});
}
2、同步get
/**
* 同步写法,需要放在子线程中使用
*/
private final String IMAGE_URL = "...";
private OkHttpClient client;
private void synchronizedGet() {
client = new OkHttpClient();
final Request request = new Request.Builder().get()
.url(IMAGE_URL)
.build();
try {
Response response = client.newCall(request).execute();
Message message = handler.obtainMessage();
if (response.isSuccessful()) {
//......
} else {
//......
}
} catch (IOException e) {
e.printStackTrace();
}
}
由于Android本身是不允许在UI线程做网络请求操作的,所以我们自己写个线程完成网络操作:
new Thread(new Runnable() {
@Override
public void run() {
synchronizedGet();
}
}).start();
四、案例:使用OkHttp的get方式下载网络图片
Demo源码下载地址:
http://download.csdn.net/detail/wei_zhi/9672863
首先是一个布局文件,一个Button和一个ImageView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.wz.okhttpdemo.MainActivity">
<Button
android:text="下载图片"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="@+id/button"
android:layout_alignParentEnd="true" />
<ImageView
android:id="@+id/imageview"
android:paddingTop="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
然后是主方法:
package com.wz.okhttpdemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private final String IMAGE_URL = "http://cdnq.duitang.com/uploads/item/201505/20/20150520102944_CiL3M.jpeg";
private static final int IS_SUCCESS = 1;
private static final int IS_FAIL = 0;
private Button button;
private ImageView imageView;
private OkHttpClient client;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case IS_SUCCESS:
byte[] bytes = (byte[]) msg.obj;
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setImageBitmap(bitmap);
break;
case IS_FAIL:
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button);
imageView = (ImageView) this.findViewById(R.id.imageview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//使用异步get
asyncGet();
//使用同步get
/* new Thread(new Runnable() {
@Override
public void run() {
synchronizedGet();
}
}).start();*/
}
});
}
/**
* 异步get,直接调用
*/
private void asyncGet() {
client = new OkHttpClient();
final Request request = new Request.Builder().get()
.url(IMAGE_URL)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = handler.obtainMessage();
if (response.isSuccessful()) {
message.what = IS_SUCCESS;
message.obj = response.body().bytes();
handler.sendMessage(message);
} else {
handler.sendEmptyMessage(IS_FAIL);
}
}
});
}
/**
* 同步写法,需要放在子线程中使用
*/
private void synchronizedGet() {
client = new OkHttpClient();
final Request request = new Request.Builder().get()
.url(IMAGE_URL)
.build();
try {
Response response = client.newCall(request).execute();
Message message = handler.obtainMessage();
if (response.isSuccessful()) {
message.what = IS_SUCCESS;
message.obj = response.body().bytes();
handler.sendMessage(message);
} else {
handler.sendEmptyMessage(IS_FAIL);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行结果:
点击下载图片:
OK,这就简单的实现了使用OkHttp来下载图片。
Demo源码下载地址:
http://download.csdn.net/detail/wei_zhi/9672863
参考:
http://m.2cto.com/net/201605/505364.html
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0824/3355.html