Android使用OkHttp实例,以及OkHttp方法封装

来源:互联网 发布:osi网络模型 编辑:程序博客网 时间:2024/05/22 10:57

本文在Android中使用OkHttp3实现数据的上传获取,图片的下载


一、在AndroidStudio中新建项目



二、在build.gradle中添加依赖


[html] view plain copy
  1. compile 'com.squareup.okhttp3:okhttp:3.6.0'  


三、新建utils包,并在包中新建OkManager.java 类

[java] view plain copy
  1. package cc.example.com.utils;  
  2.   
  3. import android.graphics.Bitmap;  
  4. import android.graphics.BitmapFactory;  
  5. import android.os.Handler;  
  6. import android.os.Looper;  
  7.   
  8. import org.json.JSONException;  
  9. import org.json.JSONObject;  
  10.   
  11. import java.io.IOException;  
  12. import java.util.Map;  
  13.   
  14. import okhttp3.Call;  
  15. import okhttp3.Callback;  
  16.   
  17. import okhttp3.FormBody;  
  18. import okhttp3.MediaType;  
  19. import okhttp3.OkHttpClient;  
  20. import okhttp3.Request;  
  21. import okhttp3.RequestBody;  
  22. import okhttp3.Response;  
  23.   
  24. /** 
  25.  * Created by Administrator on 2017/2/15 0015. 
  26.  * 封装工具类 
  27.  * 这一个类主要将OkHttp3工具类进行封装,用于对数据的传输,包括Spring,Json,img,表单等数据的提交与获取 
  28.  */  
  29. public class OkManager {  
  30.     private OkHttpClient client;  
  31.     private volatile static OkManager manager;   //防止多个线程访问时  
  32.     private final String TAG = OkManager.class.getSimpleName();  //获得类名  
  33.     private Handler handler;  
  34.   
  35.     //提交json数据  
  36.     private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");  
  37.     //提交字符串数据  
  38.     private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown;charset=utf-8");  
  39.   
  40.     private OkManager() {  
  41.         client = new OkHttpClient();  
  42.         handler = new Handler(Looper.getMainLooper());  
  43.     }  
  44.   
  45.     //采用单例模式获取对象  
  46.     public static OkManager getInstance() {  
  47.         OkManager instance = null;  
  48.         if (manager == null) {  
  49.             synchronized (OkManager.class) {                //同步代码块  
  50.                 if (instance == null) {  
  51.                     instance = new OkManager();  
  52.                     manager = instance;  
  53.                 }  
  54.             }  
  55.         }  
  56.         return instance;  
  57.     }  
  58.   
  59.     /** 
  60.      * 请求返回的是JSON字符串 
  61.      * 
  62.      * @param jsonValue 
  63.      * @param callBack 
  64.      */  
  65.     private void onSuccessJsonStringMethod(final String jsonValue, final Fun1 callBack) {  
  66.         handler.post(new Runnable() {  
  67.             @Override  
  68.             public void run() {  
  69.                 if (callBack != null) {  
  70.                     try {  
  71.                         callBack.onResponse(jsonValue);  
  72.                     } catch (Exception e) {  
  73.   
  74.                     }  
  75.                 }  
  76.             }  
  77.         });  
  78.   
  79.     }  
  80.   
  81.     /** 
  82.      * 请求返回相应结果的是Json对象 
  83.      * 
  84.      * @param jsonValue 
  85.      * @param callBack 
  86.      */  
  87.     private void onSuccessJsonObjectMethod(final String jsonValue, final Fun4 callBack) {  
  88.         handler.post(new Runnable() {  
  89.             @Override  
  90.             public void run() {  
  91.                 if (callBack != null) {  
  92.                     try {  
  93.                         callBack.onResponse(new JSONObject(jsonValue));  
  94.                     } catch (JSONException e) {  
  95.   
  96.                     }  
  97.                 }  
  98.             }  
  99.         });  
  100.     }  
  101.   
  102.     /** 
  103.      * 返回响应的对象是一个字节数组 
  104.      * 
  105.      * @param data 
  106.      * @param callBack 
  107.      */  
  108.     private void onSuccessByteMethod(final byte[] data, final Fun2 callBack) {  
  109.         handler.post(new Runnable() {  
  110.             @Override  
  111.             public void run() {  
  112.                 if (callBack != null) {  
  113.                     try {  
  114.                         callBack.onResponse(data);  
  115.                     } catch (Exception e) {  
  116.   
  117.                     }  
  118.                 }  
  119.             }  
  120.         });  
  121.     }  
  122.   
  123.     private void onSuccessImgMethod(final Bitmap bitmap, final Fun3 callBack) {  
  124.         handler.post(new Runnable() {  
  125.             @Override  
  126.             public void run() {  
  127.                 if (callBack != null) {  
  128.                     try {  
  129.                         callBack.onResponse(bitmap);  
  130.                     } catch (Exception e) {  
  131.   
  132.                     }  
  133.   
  134.                 }  
  135.             }  
  136.         });  
  137.     }  
  138.   
  139.     /** 
  140.      * 同步请求,在Android开发中不常用,因为会阻塞UI线程 
  141.      * 
  142.      * @param url 
  143.      * @return 
  144.      */  
  145.   
  146.     public String synaGetByUrl(String url) {  
  147.         //构建一个Request请求  
  148.         Request request = new Request.Builder().url(url).build();  
  149.         Response response = null;  
  150.         try {  
  151.             response = client.newCall(request).execute();  //execute用于同步请求数据  
  152.             if (response.isSuccessful()) {  
  153.                 return response.body().string();  
  154.             }  
  155.         } catch (Exception e) {  
  156.   
  157.         }  
  158.         return null;  
  159.     }  
  160.   
  161.     /** 
  162.      * 异步请求,请求返回Json字符串 
  163.      * 
  164.      * @param url 
  165.      * @param callback 
  166.      */  
  167.     public void asyncJsonStringByURL(String url, final Fun1 callback) {  
  168.         final Request request = new Request.Builder().url(url).build();  
  169.         client.newCall(request).enqueue(new Callback() {  
  170.             //enqueue是调用了一个入队的方法  
  171.             @Override  
  172.             public void onFailure(Call call, IOException e) {  
  173.                 e.printStackTrace();  
  174.             }  
  175.   
  176.             @Override  
  177.             public void onResponse(Call call, Response response) throws IOException {  
  178.                 if (response != null && response.isSuccessful()) {  
  179.                     onSuccessJsonStringMethod(response.body().string(), callback);  
  180.                 }  
  181.             }  
  182.         });  
  183.   
  184.     }  
  185.   
  186.     /** 
  187.      * 异步请求,请求返回Json对象 
  188.      * 
  189.      * @param url 
  190.      * @param callback 
  191.      */  
  192.   
  193.     public void asyncJsonObjectByUrl(String url, final Fun4 callback) {  
  194.         final Request request = new Request.Builder().url(url).build();  
  195.         client.newCall(request).enqueue(new Callback() {  
  196.             @Override  
  197.             public void onFailure(Call call, IOException e) {  
  198.                 e.printStackTrace();  
  199.             }  
  200.   
  201.             @Override  
  202.             public void onResponse(Call call, Response response) throws IOException {  
  203.                 if (response != null && response.isSuccessful()) {  
  204.                     onSuccessJsonObjectMethod(response.body().string(), callback);  
  205.                 }  
  206.             }  
  207.         });  
  208.   
  209.     }  
  210.   
  211.     /** 
  212.      * 异步请求,请求返回的byte字节数组 
  213.      * 
  214.      * @param url 
  215.      * @param callback 
  216.      */  
  217.     public void asyncGetByteByUrl(String url, final Fun2 callback) {  
  218.         final Request request = new Request.Builder().url(url).build();  
  219.         client.newCall(request).enqueue(new Callback() {  
  220.   
  221.             @Override  
  222.             public void onFailure(Call call, IOException e) {  
  223.   
  224.             }  
  225.   
  226.             @Override  
  227.             public void onResponse(Call call, Response response) throws IOException {  
  228.                 if (response != null && response.isSuccessful()) {  
  229.                     onSuccessByteMethod(response.body().bytes(), callback);  
  230.                 }  
  231.             }  
  232.         });  
  233.     }  
  234.   
  235.     /** 
  236.      * 异步请求,请求返回图片 
  237.      * 
  238.      * @param url 
  239.      * @param callback 
  240.      */  
  241.     public void asyncDownLoadImgtByUrl(String url, final Fun3 callback) {  
  242.         final Request request = new Request.Builder().url(url).build();  
  243.         client.newCall(request).enqueue(new Callback() {  
  244.             @Override  
  245.             public void onFailure(Call call, IOException e) {  
  246.                 e.printStackTrace();  
  247.             }  
  248.   
  249.             @Override  
  250.             public void onResponse(Call call, Response response) throws IOException {  
  251.                 if (response != null && response.isSuccessful()) {  
  252.                     byte[] data = response.body().bytes();  
  253.                     Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
  254.                     onSuccessImgMethod(bitmap, callback);  
  255.   
  256.                     System.out.println(data.length);  
  257.                 }  
  258.             }  
  259.         });  
  260.   
  261.     }  
  262.   
  263.     /** 
  264.      * 模拟表单的提交 
  265.      * 
  266.      * @param url 
  267.      * @param param 
  268.      * @param callback 
  269.      */  
  270.     public void sendComplexForm(String url, Map<String, String> param, final Fun4 callback) {  
  271.         FormBody.Builder form_builder = new FormBody.Builder();  //表单对象,包含以input开始的对象,模拟一个表单操作,以HTML表单为主  
  272.         //如果键值对不为空,且值不为空  
  273.         if (param != null && !param.isEmpty()) {  
  274.             //循环这个表单,zengqiang for循环  
  275.             for (Map.Entry<String, String> entry : param.entrySet()) {  
  276.                 form_builder.add(entry.getKey(), entry.getValue());  
  277.             }  
  278.         }  
  279.         //声明一个请求对象体  
  280.         RequestBody request_body = form_builder.build();  
  281.         //采用post的方式进行提交  
  282.         Request request = new Request.Builder().url(url).post(request_body).build();  
  283.         client.newCall(request).enqueue(new Callback() {  
  284.             @Override  
  285.             public void onFailure(Call call, IOException e) {  
  286.   
  287.             }  
  288.   
  289.             @Override  
  290.             public void onResponse(Call call, Response response) throws IOException {  
  291.                 if (response != null && response.isSuccessful()) {  
  292.                     onSuccessJsonObjectMethod(response.body().string(), callback);  
  293.                 }  
  294.             }  
  295.         });  
  296.     }  
  297.   
  298.     /** 
  299.      * 向服务器提交String请求 
  300.      * 
  301.      * @param url 
  302.      * @param content 
  303.      * @param callback 
  304.      */  
  305.     public void sendStringByPost(String url, String content, final Fun4 callback) {  
  306.         Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, content)).build();  
  307.         client.newCall(request).enqueue(new Callback() {  
  308.             @Override  
  309.             public void onFailure(Call call, IOException e) {  
  310.   
  311.             }  
  312.   
  313.             @Override  
  314.             public void onResponse(Call call, Response response) throws IOException {  
  315.                 if (response != null && response.isSuccessful()) {  
  316.                     onSuccessJsonObjectMethod(response.body().string(), callback);  
  317.                 }  
  318.             }  
  319.         });  
  320.   
  321.     }  
  322.   
  323.     //回调  
  324.     public interface Fun1 {  
  325.         void onResponse(String result);  
  326.     }  
  327.   
  328.     interface Fun2 {  
  329.         void onResponse(byte[] result);  
  330.     }  
  331.   
  332.     public interface Fun3 {  
  333.         void onResponse(Bitmap bitmap);  
  334.     }  
  335.   
  336.     public interface Fun4 {  
  337.         void onResponse(JSONObject jsonObject);  
  338.     }  
  339.   
  340.   
  341. }  
四、编写activity_main.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:orientation="vertical">  
  8.   
  9.     <Button  
  10.         android:id="@+id/test"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="50dp"  
  13.         android:text="用于获取图片" />  
  14.   
  15.     <ImageView  
  16.         android:id="@+id/testImageView"  
  17.         android:layout_width="match_parent"  
  18.         android:layout_height="100dp"  
  19.   
  20.         />  
  21.   
  22.     <Button  
  23.         android:id="@+id/getjson"  
  24.         android:layout_width="match_parent"  
  25.         android:layout_height="50dp"  
  26.         android:text="获取Json数据请求" />  
  27.   
  28.     <Button  
  29.         android:id="@+id/button3"  
  30.   
  31.         android:layout_width="match_parent"  
  32.         android:layout_height="50dp"  
  33.         android:text="用于登录验证" />  
  34.   
  35.   
  36. </LinearLayout>  

五、编写MainActivity.java

[java] view plain copy
  1. package cc.example.com.datatransimission;  
  2.   
  3.   
  4. import android.graphics.Bitmap;  
  5. import android.os.Bundle;  
  6.   
  7.   
  8. import android.support.v7.app.AppCompatActivity;  
  9.   
  10. import android.util.Log;  
  11. import android.view.View;  
  12.   
  13. import android.widget.Button;  
  14. import android.widget.ImageView;  
  15.   
  16.   
  17. import org.json.JSONObject;  
  18.   
  19. import java.io.IOException;  
  20. import java.util.HashMap;  
  21. import java.util.Map;  
  22.   
  23.   
  24. import cc.example.com.utils.OkManager;  
  25. import okhttp3.Call;  
  26. import okhttp3.Callback;  
  27. import okhttp3.OkHttpClient;  
  28. import okhttp3.Request;  
  29. import okhttp3.Response;  
  30.   
  31.   
  32. public class MainActivity extends AppCompatActivity {  
  33.   
  34.     private Button testButton, getJsonButton, button3;  
  35.     private ImageView testImageView;  
  36.     private final static int SUCCESS_SATUS = 1;  
  37.     private final static int FAILURE = 0;  
  38.     private final static String Tag = MainActivity.class.getSimpleName();  
  39.   
  40.   
  41.     private OkManager manager;  
  42.   
  43.     private OkHttpClient clients;  
  44.   
  45.     //图片下载的请求地址  
  46.     private String img_path = "http://192.168.191.1:8080/OkHttp3Server/UploadDownloadServlet?method=download";  
  47.     //请求返回值为Json数组  
  48.     private String jsonpath = "http://192.168.191.1:8080/OkHttp3Server/ServletJson";  
  49.     //登录验证请求  
  50.     private String login_path="http://192.168.191.1:8080/OkHttp3Server/OkHttpLoginServlet";  
  51.   
  52.   
  53.     @Override  
  54.     protected void onCreate(Bundle savedInstanceState) {  
  55.         super.onCreate(savedInstanceState);  
  56.         setContentView(R.layout.activity_main);  
  57.         testButton = (Button) findViewById(R.id.test);  
  58.         getJsonButton = (Button) findViewById(R.id.getjson);  
  59.   
  60.   
  61.         testImageView = (ImageView) findViewById(R.id.testImageView);  
  62.         button3 = (Button) findViewById(R.id.button3);  
  63.   
  64.         //-----------------------------------------------------------------------------------------  
  65.         manager = OkManager.getInstance();  
  66.         getJsonButton.setOnClickListener(new View.OnClickListener() {  
  67.             @Override  
  68.             public void onClick(View v) {  
  69.                 manager.asyncJsonStringByURL(jsonpath, new OkManager.Fun1() {  
  70.                     @Override  
  71.                     public void onResponse(String result) {  
  72.                         Log.i(Tag, result);   //获取JSON字符串  
  73.                     }  
  74.                 });  
  75.             }  
  76.         });  
  77.         //-------------------------------------------------------------------------  
  78.         //用于登录请求测试,登录用户名和登录密码应该Sewrver上的对应  
  79.         button3.setOnClickListener(new View.OnClickListener() {  
  80.             @Override  
  81.             public void onClick(View v) {  
  82.                 Map<String, String> map = new HashMap<String, String>();  
  83.                 map.put("username""123");  
  84.                 map.put("password""123");  
  85.                 manager.sendComplexForm(login_path, map, new OkManager.Fun4() {  
  86.                     @Override  
  87.                     public void onResponse(JSONObject jsonObject) {  
  88.                         Log.i(Tag, jsonObject.toString());  
  89.                     }  
  90.                 });  
  91.             }  
  92.         });  
  93.         testButton.setOnClickListener(new View.OnClickListener() {  
  94.             @Override  
  95.             public void onClick(View v) {  
  96.                 manager.asyncDownLoadImgtByUrl(img_path, new OkManager.Fun3() {  
  97.                     @Override  
  98.                     public void onResponse(Bitmap bitmap) {  
  99.                         // testImageView.setBackgroundResource(0);  
  100.                         testImageView.setImageBitmap(bitmap);  
  101.                         Log.i(Tag, "231541645");  
  102.                     }  
  103.                 });  
  104.             }  
  105.         });  
  106.   
  107.     }  
  108.   
  109.   
  110. }  

六、运行结果:




七:客户端Android源码地址:https://github.com/HankZhaoSE/OkHttp3

        服务器地址:https://github.com/HankZhaoSE/OkHttp3Server   


原创粉丝点击