Android的Okhttp框架之post、get用法讲解(落雨敏)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lin857/article/details/54694441

         前言: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

猜你喜欢

转载自blog.csdn.net/lin857/article/details/54694441