Android的Okhttp框架之post、get用法講解(落雨敏)
前言:okhttp作為Android主流網路框架之一,但在近日okhttp網路請求卻比較火,主要原因是在谷歌官方在6.0以後在Android sdk已經移除了httpClient,加入我們okHttp。在常用的框架之中( volley,Retrofit,OKHttp等),我比較喜歡使用OKHttp。OkHttp是一個現代,快速,高效的Http client,OkHttp使用Okio來大大簡化資料的訪問與儲存,Okio是一個增強 java.io 和java.nio的庫。(最下面例項原始碼下載)
博主在此介紹常用功能的使用:
1、Get請求(同步和非同步);
2、POST請求表單(key-value);
3、POST請求提交(JSON/String等);
4、檔案下載;
5、檔案上傳;
6、圖片快取載入
首先,下載okhttp、okio的jar包,將其包加入到專案中 ,方便使用。post、get、上傳、下載等,都封裝在一個工具類,方便呼叫。
(1)工具類——UtilOkHttp
//post請求編碼
private static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
//設定請求超時等
static {
client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
client.newBuilder().readTimeout(10, TimeUnit.SECONDS);
client.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
}
//建立物件
private static OkHttpClient client=new OkHttpClient();
//-------------------------------同步get-------------------------------------------------------------------------------------------
public static void get_T(String url,final Handler handler) { final Request request = new Request.Builder().url(url).build(); new Thread(new Runnable() { @Override public void run() { try { Response response=client.newCall(request).execute(); if( response.isSuccessful()){ returns=response.body().string(); Log.i("test","get同步請求成功"+ returns); Message msg1=new Message(); msg1.what=1; msg1.obj=returns; handler.sendMessage(msg1); } else{ returns="請求失敗"; Log.i("test","get同步請求失敗"+ returns); } } catch (IOException e) { e.printStackTrace(); } } }).start(); }
//-----------------------------------get非同步-------------------------------------------------------------------------------------------
public static void get_Y(String url,final Handler handler){
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","get非同步請求成功,返回returns的值:"+ returns);
Message msg2=new Message();
msg2.what=2;
msg2.obj=returns;
handler.sendMessage(msg2);
}
else{
Log.i("test","get非同步請求成功,返回NO:");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","get非同步請求失敗"+ arg0.toString());
}
});
}
//------------------------------------post表單------------------------------------------------------------------------------------------------
public static void post_Form(String url,String key,String value,final Handler handler){
FormBody requestBody=new FormBody.Builder().add(key, value).build();
Request request=new Request.Builder().url(url).addHeader("Content-Type", "application/json; charset=UTF-8") .post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post表單請求成功,返回ok=returns:"+returns);
Message msg3=new Message();
msg3.what=3;
msg3.obj=returns;
handler.sendMessage(msg3);
}
else {
Log.i("test","post表單請求成功,返回NO");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","post表單請求失敗");
}
});
Log.i("test","post表單請求成功,方法完成"+returns);
}
//--------------------------------------post的josn-----------------------------------------------------------------------------------------------
public static void post_Json(String url, String json){
RequestBody body=RequestBody.create(JSON, json);
Request request=new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post-json請求成功,返回ok:"+returns);
}
else {
Log.i("test","post-json請求成功,返回NO");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","post-json請求失敗"+arg0.toString());
}
});
}
//---------------------------------------get非同步請求圖片-------------------------------------------------------------------------------------
public static void get_Bitmap(String url,final Handler handler){
Request request=new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
byte [] by=arg1.body().bytes();
bitmap=BitmapFactory.decodeByteArray(by, 0, by.length);
Log.i("test", "get請求圖片成功,返回OK");
Message msg4=new Message();
msg4.what=4;
msg4.obj=bitmap;
handler.sendMessage(msg4);
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "get非同步請求圖片失敗");
}
});
}
//----------------------------------------get非同步檔案下載-------------------------------------------------------------------------------------
public static void get_Y_FileDown(String url,final String path_up,final String saveName,final Handler handler){
Request request=new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
InputStream is = arg1.body().byteStream();// 把請求成功的response轉為位元組流
FileOutputStream os = new FileOutputStream(new File(path_up,saveName));//檔案輸出流,本地存
byte[] buffer = new byte[2048];//每次迴圈讀取2K的資料
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
Log.i("test", "圖片大小:"+len);
}
os.flush();
os.close();
is.close();
Log.i("test", "get非同步請求檔案下載成功,返回完成資料");
returns="下載成功";
Message msg5=new Message();
msg5.what=5;
msg5.obj=returns;
handler.sendMessage(msg5);
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "get非同步請求檔案下載失敗");
returns="下載請求失敗";
}
});
}
//----------------------------------------post檔案上傳-----------------------------------------------------------------------------------------
public static String post_Y_FileUp(String url,String path, String fileName,final Handler handler){
//上傳圖片
File f1 = new File( path+ fileName);
Log.i("test", "檔案路徑:"+path+fileName);
if(f1.exists()){
Log.i("test", "檔案存在");
}
else {
Log.i("test", "檔案不存在");
}
RequestBody fileBody1=RequestBody.create(MediaType.parse("application/octet-stream") , f1);
//form的分割線,自己定義
String boundary = "xx--------------------------------------------------------------xx";
MultipartBody mBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)
//.addFormDataPart("lin" , "123")
.addFormDataPart("file" ,fileName, fileBody1)
.build();
Request request=new Request.Builder().url(url).post(fileBody1).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post檔案上傳成功,返回ok=returns:"+returns);
Message msg6=new Message();
msg6.what=6;
msg6.obj=returns;
handler.sendMessage(msg6);
}
else {
Log.i("test", "post非同步請求檔案上傳成功,未完成");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "post非同步請求檔案上傳失敗");
}
});
return fileName;
}
}
//-----------------------------------------------封裝類(全部程式碼)----------------------------------------------------------------------
package com.tools;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class UtilOkHttp {
private static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");//post請求編碼
private static String returns;//返回字元
private static Bitmap bitmap;//返回圖片
private static OkHttpClient client=new OkHttpClient();
static {
client.newBuilder().connectTimeout(10, TimeUnit.SECONDS);
client.newBuilder().readTimeout(10, TimeUnit.SECONDS);
client.newBuilder().writeTimeout(10, TimeUnit.SECONDS);
}
//-------------------------------同步get-------------------------------------------
public static void get_T(String url,final Handler handler) {
final Request request = new Request.Builder().url(url).build();
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response=client.newCall(request).execute();
if( response.isSuccessful()){
returns=response.body().string();
Log.i("test","get同步請求成功"+ returns);
Message msg1=new Message();
msg1.what=1;
msg1.obj=returns;
handler.sendMessage(msg1);
}
else{
returns="請求失敗";
Log.i("test","get同步請求失敗"+ returns);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//-----------------------------------get非同步-----------------------------------------------------
public static void get_Y(String url,final Handler handler){
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","get非同步請求成功,返回returns的值:"+ returns);
Message msg2=new Message();
msg2.what=2;
msg2.obj=returns;
handler.sendMessage(msg2);
}
else{
Log.i("test","get非同步請求成功,返回NO:");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","get非同步請求失敗"+ arg0.toString());
}
});
}
//------------------------------------post表單------------------------------------------------
public static void post_Form(String url,String key,String value,final Handler handler){
FormBody requestBody=new FormBody.Builder().add(key, value).build();
Request request=new Request.Builder().url(url).addHeader("Content-Type", "application/json; charset=UTF-8") .post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post表單請求成功,返回ok=returns:"+returns);
Message msg3=new Message();
msg3.what=3;
msg3.obj=returns;
handler.sendMessage(msg3);
}
else {
Log.i("test","post表單請求成功,返回NO");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","post表單請求失敗");
}
});
Log.i("test","post表單請求成功,方法完成"+returns);
}
//-----------------------------------post的josn-------------------------------------
public static void post_Json(String url, String json){
RequestBody body=RequestBody.create(JSON, json);
Request request=new Request.Builder().url(url).post(body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post-json請求成功,返回ok:"+returns);
}
else {
Log.i("test","post-json請求成功,返回NO");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test","post-json請求失敗"+arg0.toString());
}
});
}
//---------------------------------------get非同步請求圖片------------------------------------------------
public static void get_Bitmap(String url,final Handler handler){
Request request=new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
byte [] by=arg1.body().bytes();
bitmap=BitmapFactory.decodeByteArray(by, 0, by.length);
Log.i("test", "get請求圖片成功,返回OK");
Message msg4=new Message();
msg4.what=4;
msg4.obj=bitmap;
handler.sendMessage(msg4);
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "get非同步請求圖片失敗");
}
});
}
//----------------------------------------get非同步檔案下載-------------------------------------------------------
public static void get_Y_FileDown(String url,final String path_up,final String saveName,final Handler handler){
Request request=new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
InputStream is = arg1.body().byteStream();// 把請求成功的response轉為位元組流
FileOutputStream os = new FileOutputStream(new File(path_up,saveName));//檔案輸出流,本地存
byte[] buffer = new byte[2048];//每次迴圈讀取2K的資料
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
Log.i("test", "圖片大小:"+len);
}
os.flush();
os.close();
is.close();
Log.i("test", "get非同步請求檔案下載成功,返回完成資料");
returns="下載成功";
Message msg5=new Message();
msg5.what=5;
msg5.obj=returns;
handler.sendMessage(msg5);
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "get非同步請求檔案下載失敗");
returns="下載請求失敗";
}
});
}
//----------------------------------------post檔案上傳-------------------------------------------------------
public static String post_Y_FileUp(String url,String path, String fileName,final Handler handler){
//上傳圖片
File f1 = new File( path+ fileName);
Log.i("test", "檔案路徑:"+path+fileName);
if(f1.exists()){
Log.i("test", "檔案存在");
}
else {
Log.i("test", "檔案不存在");
}
RequestBody fileBody1=RequestBody.create(MediaType.parse("application/octet-stream") , f1);
//form的分割線,自己定義
String boundary = "xx--------------------------------------------------------------xx";
MultipartBody mBody = new MultipartBody.Builder(boundary).setType(MultipartBody.FORM)
//.addFormDataPart("lin" , "123")
.addFormDataPart("file" ,fileName, fileBody1)
.build();
Request request=new Request.Builder().url(url).post(fileBody1).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call arg0, Response arg1) throws IOException {
if(arg1.isSuccessful()){
returns=arg1.body().string();
Log.i("test","post檔案上傳成功,返回ok=returns:"+returns);
Message msg6=new Message();
msg6.what=6;
msg6.obj=returns;
handler.sendMessage(msg6);
}
else {
Log.i("test", "post非同步請求檔案上傳成功,未完成");
}
}
@Override
public void onFailure(Call arg0, IOException arg1) {
Log.i("test", "post非同步請求檔案上傳失敗");
}
});
return fileName;
}
}
(2)、Activity的呼叫(直接上全部原始碼)
package com.example.okhttpt;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tools.UtilOkHttp;
public class MainActivity extends Activity {
private Button bt_get,bt_getY,bt_post,bt_fileup,bt_filedown,bt_img;
private ImageView iv;
private TextView tv;
private String back_str;
private String url="http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9";
private String posturl="https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
private String url2 = "http://www.kuaidi100.com/query?type=yuantong&postid=229728279823";
private String url3="http://image.tianjimedia.com/uploadImages/upload/20161225/pffzbsobi4ujpg.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private Handler handler=new Handler(){
public void handleMessage(Message msg) {
if(msg.what==1){
tv.setText(msg.obj+"");
}
if(msg.what==2){
tv.setText(msg.obj+"");
}
if(msg.what==3){
tv.setText(msg.obj+"");
}
if(msg.what==4){
iv.setImageBitmap((Bitmap) msg.obj);
}
if(msg.what==5){
tv.setText(msg.obj+"");
}
if(msg.what==6){
tv.setText(msg.obj+"");
}
};
};
private void init() {
bt_get=(Button) findViewById(R.id.bt_get);
bt_get.setOnClickListener(new MyListener());
bt_getY=(Button) findViewById(R.id.bt_getY);
bt_getY.setOnClickListener(new MyListener());
bt_post=(Button) findViewById(R.id.bt_post);
bt_post.setOnClickListener(new MyListener());
bt_fileup=(Button) findViewById(R.id.bt_fileup);
bt_fileup.setOnClickListener(new MyListener());
bt_filedown=(Button) findViewById(R.id.bt_filedown);
bt_filedown.setOnClickListener(new MyListener());
bt_img=(Button) findViewById(R.id.bt_img);
bt_img.setOnClickListener(new MyListener());
iv=(ImageView) findViewById(R.id.img);
tv=(TextView) findViewById(R.id.tv);
}
class MyListener implements OnClickListener{
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_get:
UtilOkHttp.get_T(url,handler);
break;
case R.id.bt_getY:
UtilOkHttp.get_Y(url2,handler);
break;
case R.id.bt_post:
UtilOkHttp.post_Form(posturl, "tel", "15850781443",handler);
break;
case R.id.bt_filedown:
String path_up=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
UtilOkHttp.get_Y_FileDown(url3, path_up, "liuyifei2.jpg",handler);
break;
case R.id.bt_img:
UtilOkHttp.get_Bitmap(url3,handler);
break;
case R.id.bt_fileup:
String url="http://192.168.1.145:8080/ServletWeb/servlet/MyServlet";
String path_Up=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()+"/";
//OkHttpUtil.post_Form(url, "chen", "520", handler);
UtilOkHttp.post_Y_FileUp(url, path_Up, "liuyifei2.jpg",handler);
break;
default:
break;
}
}
}
}
(3)、xml全部原始碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.okhttpt.MainActivity"
>
<Button
android:id="@+id/bt_get"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="同步get請求"/>
<Button
android:id="@+id/bt_getY"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="非同步get請求"/>
<Button
android:id="@+id/bt_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post表單請求或json"/>
<Button
android:id="@+id/bt_filedown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get非同步下載檔案"/>
<Button
android:id="@+id/bt_fileup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post上傳檔案"/>
<Button
android:id="@+id/bt_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="get非同步請求圖片"/>
<ImageView
android:id="@+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
/>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:text="內容:"/>
</LinearLayout>
(4)、需要的許可權
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
(5)、效果圖(部分方法效果圖,剩下的截圖交給你們了)
(6)、免費下載全部例項程式碼(註釋更全,更完善)
http://download.csdn.net/detail/lin857/9743847