一、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