(1)工具类——
//post请求编码
finalJSON= .parse("/json; =utf-8");
//设置请求超时等
{
.().(10, .);
.().(10, .);
.().(10, .);
//创建对象
=new ();
//-------------------------------同步get-------------------------------------------------------------------------------------------
public static voidget_T(String url,final Handler handler) {final Request request = new Request.Builder().url(url).build();new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic 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:");}}@Overridepublic 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() {@Overridepublic 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");} }@Overridepublic 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() {@Overridepublic 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");}}@Overridepublic 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() {@Overridepublic 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);} @Overridepublic 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() {@Overridepublic 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);}@Overridepublic 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() {@Overridepublic 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异步请求文件上传成功,未完成");}}@Overridepublic 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 Stringreturns;//返回字符private static Bitmapbitmap;//返回图片private staticOkHttpClient 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 voidget_T(String url,final Handler handler) {final Request request = new Request.Builder().url(url).build();new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic 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:");}}@Overridepublic 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() {@Overridepublic 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");} }@Overridepublic 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() {@Overridepublic 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");}}@Overridepublic 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() {@Overridepublic 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);} @Overridepublic 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() {@Overridepublic 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);}@Overridepublic 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() {@Overridepublic 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异步请求文件上传成功,未完成");}}@Overridepublic void onFailure(Call arg0, IOException arg1) {Log.i("test", "post异步请求文件上传失败");}});return fileName;}}
(2)、的调用(直接上全部源码)
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";@Overrideprotected 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{@Overridepublic 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全部源码
(4)、需要的权限
(5)、效果图(部分方法效果图,剩下的截图交给你们了)
文章插图
文章插图
文章插图
【落雨敏Android的Okhttp框架之post、get用法讲解】(6)、免费下载全部实例代码(注释更全,更完善)
- Android bitmap 释放 解决Error create Hprof f
- 解决在SDK23环境下android:singleLine=true的singl
- 敏捷软件开发与传统软件工程
- Android Q 可折叠屏模拟器
- android 五角星坐标,GitHub
- Android移动开发第一次作业
- 二 Android折叠屏开发学习
- 敏捷25年:历史阶段与中坚力量
- 基础版 Android 开发规范
- Android 10,11 文件存储