当前位置:   article > 正文

Android项目中okhttp3的简易封装和使用_android okhttp3

android okhttp3

1、所有文件:

2、OkHttpUtil类

这个类主要用于初始化okhttp和发送http请求。

  1. public class OkHttpUtil{
  2. private static OkHttpClient mOkHttpClient = null;
  3. //Call this method in the Application class. ---> onCreate() method.
  4. //Thus we can get only one instance of httpClient in the whole app.
  5. public static void init(){
  6. if (mOkHttpClient == null) {
  7. OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
  8. .connectTimeout(5000, TimeUnit.MILLISECONDS)
  9. .readTimeout(5000, TimeUnit.MILLISECONDS)
  10. .writeTimeout(5000, TimeUnit.MILLISECONDS)
  11. .sslSocketFactory(RxUtils.createSSLSocketFactory(),new RxUtils.TrustAllManager())
  12. .hostnameVerifier(new RxUtils.TrustAllHostnameVerifier());
  13. mOkHttpClient = builder.build();
  14. }
  15. }
  16. //If GET method needs some other params, just need to add a HaspMap. Refer to:https://www.imooc.com/video/18685
  17. public static void get(String url, OkHttpCallBack okHttpCallback){
  18. Call call = null;
  19. try{
  20. Request request = new Request.Builder().url(url).build();
  21. call = mOkHttpClient.newCall(request);
  22. call.enqueue(okHttpCallback);
  23. }catch(Exception ex){
  24. ex.printStackTrace();
  25. }
  26. }
  27. public static void post(String url, OkHttpCallBack okHttpCallback, HashMap<String, String> bodyMap){
  28. Call call = null;
  29. try{
  30. FormBody.Builder builder = new FormBody.Builder();
  31. for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
  32. builder.add(entry.getKey(), entry.getValue());
  33. }
  34. RequestBody body = builder.build();
  35. Request.Builder builderRequest = new Request.Builder();
  36. // builderRequest.headers(new Headers())
  37. Request request = builderRequest.post(body).url(url).build();
  38. call = mOkHttpClient.newCall(request);
  39. call.enqueue(okHttpCallback);
  40. }catch(Exception ex){
  41. ex.printStackTrace();
  42. }
  43. }
  44. public static void postHasFile(String url, OkHttpCallBack okHttpCallback, HashMap<String, String> bodyMap, String filesKey, List<File> files){
  45. Call call = null;
  46. try{
  47. MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
  48. multipartBodyBuilder.setType(MultipartBody.FORM);
  49. for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
  50. multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
  51. }
  52. //遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
  53. if (files != null){
  54. for (File file : files) {
  55. multipartBodyBuilder.addFormDataPart(filesKey, file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
  56. }
  57. }
  58. RequestBody body = multipartBodyBuilder.build();
  59. Request.Builder builderRequest = new Request.Builder();
  60. // builderRequest.headers(new Headers())
  61. Request request = builderRequest.post(body).url(url).build();
  62. call = mOkHttpClient.newCall(request);
  63. call.enqueue(okHttpCallback);
  64. }catch(Exception ex){
  65. ex.printStackTrace();
  66. }
  67. }
  68. }

1、在application中调用init方法初始化okhttp。

2、使用post方法:

(1)第一个(post)是不上传图片的请求,只需传入请求url、map形式的上传参数,一个请求监听。

(2)第二个(postHasFile)为上传文件请求,本人项目中只需上传一个图片列表,所以只增加了

String filesKey, List<File> files

两个参数。如果有其他需求,可以修改此处代码:

MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
multipartBodyBuilder.setType(MultipartBody.FORM);
for (HashMap.Entry<String, String> entry : bodyMap.entrySet()) {
    multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
//遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
if (files != null){
    for (File file : files) {
        multipartBodyBuilder.addFormDataPart(filesKey, file.getName(), RequestBody.create(MediaType.parse("image/png"), file));
    }
}

2、OkHttpCallBack

这个类简单封装了Okhttp的callback方法并以jsonObject回调给请求。

  1. import android.util.Log;
  2. import com.google.gson.Gson;
  3. import org.json.JSONException;
  4. import org.json.JSONObject;
  5. import org.json.JSONTokener;
  6. import java.io.IOException;
  7. import okhttp3.Call;
  8. import okhttp3.Callback;
  9. import okhttp3.Response;
  10. //The class to deal with the OkHttpCallback
  11. public abstract class OkHttpCallBack implements Callback {
  12. public abstract void onSuccess(final Call call, JSONObject jsonObject);
  13. @Override
  14. public void onResponse(Call call, Response response) throws IOException {
  15. Log.d("OkHttpCallBackResponse:",call.toString()+"\r\n//reponse"+response.toString()+"\r\nresponse.headers:"+response.headers()
  16. +"\r\nreponse.message:"+response.message());
  17. if (response != null) {
  18. String str = response.body().string().trim();
  19. Log.d("OkHttpCallBackResponse","//body::"+str);
  20. if (response.isSuccessful()) {
  21. try{
  22. JSONObject object = (JSONObject)new JSONTokener(str).nextValue();
  23. if (object != null) {
  24. onSuccess(call, object);
  25. }else{
  26. onFailure(call, null);
  27. }
  28. }catch(JSONException e) {
  29. e.printStackTrace();
  30. onFailure(call, null);
  31. }
  32. }else{
  33. onFailure(call, null);
  34. }
  35. }
  36. }
  37. @Override
  38. public void onFailure(Call call, IOException e){
  39. Log.d("OkHttpCallBackFail",call.toString()+"//"+e.toString());
  40. }
  41. }

3、RxUtils 

这个类是为了配置请求证书 (https需要)。

  1. import java.security.SecureRandom;
  2. import java.security.cert.CertificateException;
  3. import java.security.cert.X509Certificate;
  4. import javax.net.ssl.HostnameVerifier;
  5. import javax.net.ssl.SSLContext;
  6. import javax.net.ssl.SSLSession;
  7. import javax.net.ssl.SSLSocketFactory;
  8. import javax.net.ssl.TrustManager;
  9. import javax.net.ssl.X509TrustManager;
  10. //在okhttp中设置信任所有证书
  11. public class RxUtils {
  12. @SuppressLint("TrulyRandom")
  13. public static SSLSocketFactory createSSLSocketFactory() {
  14. SSLSocketFactory sSLSocketFactory = null;
  15. try {
  16. SSLContext sc = SSLContext.getInstance("TLS");
  17. sc.init(null, new TrustManager[]{new TrustAllManager()},
  18. new SecureRandom());
  19. sSLSocketFactory = sc.getSocketFactory();
  20. } catch (Exception ignored) {
  21. }
  22. return sSLSocketFactory;
  23. }
  24. public static class TrustAllManager implements X509TrustManager {
  25. @SuppressLint("TrustAllX509TrustManager")
  26. @Override
  27. public void checkClientTrusted(X509Certificate[] chain, String authType)
  28. throws CertificateException {
  29. }
  30. @SuppressLint("TrustAllX509TrustManager")
  31. @Override
  32. public void checkServerTrusted(X509Certificate[] chain, String authType)
  33. throws CertificateException {
  34. }
  35. @Override
  36. public X509Certificate[] getAcceptedIssuers() {
  37. return new X509Certificate[0];
  38. }
  39. }
  40. public static class TrustAllHostnameVerifier implements HostnameVerifier {
  41. @SuppressLint("BadHostnameVerifier")
  42. @Override
  43. public boolean verify(String hostname, SSLSession session) {
  44. return true;
  45. }
  46. }
  47. }

4、 NetConfig

此类主要写了baseurl和各个请求接口url。

  1. public class NetConfig {
  2. public static String BASE_URL = "http://111.111.1.111:8081/";
  3. //登录
  4. public static String LOGIN = BASE_URL+"mobileApi/user/login";
  5. }

5、ApiUtil

这个类为每个请求的基类

  1. import android.os.Handler;
  2. import android.os.Message;
  3. import android.util.Log;
  4. import androidx.annotation.NonNull;
  5. import org.json.JSONObject;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import okhttp3.Call;
  11. public abstract class ApiUtil {
  12. private ApiListener mApiListener = null;
  13. private static final int SUCCESS = 1;
  14. private static final int FAIRURE = 2;
  15. private Handler handler = new Handler(){
  16. @Override
  17. public void handleMessage(@NonNull Message msg) {
  18. super.handleMessage(msg);
  19. switch (msg.what){
  20. case SUCCESS:
  21. mApiListener.success(ApiUtil.this);
  22. break;
  23. case FAIRURE:
  24. mApiListener.failrure(ApiUtil.this);
  25. break;
  26. }
  27. }
  28. };
  29. public boolean mStatus = false;
  30. public String msg = "请求失败";
  31. public String TAG = this.getClass().toString();
  32. private OkHttpCallBack mSendListener = new OkHttpCallBack(){
  33. @Override
  34. public void onSuccess(Call call, JSONObject jsonObject) {
  35. ApiUtil.this.mStatus = jsonObject.optBoolean("status");
  36. ApiUtil.this.msg = jsonObject.optString("msg");
  37. if (mStatus) {
  38. try{
  39. parseData(jsonObject);
  40. handler.sendEmptyMessage(SUCCESS);
  41. }catch(IOException e){
  42. handler.sendEmptyMessage(FAIRURE);
  43. e.printStackTrace();
  44. } catch (Exception e) {
  45. handler.sendEmptyMessage(FAIRURE);
  46. e.printStackTrace();
  47. }
  48. }else{
  49. handler.sendEmptyMessage(FAIRURE);
  50. }
  51. }
  52. @Override
  53. public void onFailure(Call call, IOException e){
  54. ApiUtil.this.msg = "链接失败";
  55. ApiUtil.this.mStatus = false;
  56. handler.sendEmptyMessage(FAIRURE);
  57. }
  58. };
  59. // public boolean isSuccess(){
  60. // return "0".equals(mStatus) || "200".equals(mStatus);
  61. // }
  62. protected abstract void parseData(JSONObject jsonObject) throws Exception;
  63. protected abstract String getUrl();
  64. //Send GET request
  65. //Listener: Tell the app whether the GET reqeust is success.
  66. public void get(ApiListener listener){
  67. mApiListener = listener;
  68. OkHttpUtil.get(getUrl(), mSendListener);
  69. }
  70. private HashMap<String, String> mBodyMap = new HashMap<>();
  71. public void addParams(String key, String value){
  72. mBodyMap.put(key, value);
  73. }
  74. public void clearParams(){
  75. mBodyMap.clear();
  76. }
  77. //Send POST request
  78. //Listener: Tell the app whether the POST reqeust is success.
  79. public void post(ApiListener listener){
  80. mApiListener = listener;
  81. OkHttpUtil.post(getUrl(), mSendListener, mBodyMap);
  82. }
  83. public void postFiles(ApiListener listener, String fileKey, List<File> fileList){
  84. mApiListener = listener;
  85. OkHttpUtil.postHasFile(getUrl(),mSendListener,mBodyMap,fileKey,fileList);
  86. }
  87. @Override
  88. public String toString() {
  89. return "ApiUtil{" +
  90. "mApiListener=" + mApiListener +
  91. ", mStatus=" + mStatus +
  92. ", msg='" + msg + '\'' +
  93. ", TAG='" + TAG + '\'' +
  94. ", mSendListener=" + mSendListener +
  95. ",\r\n mBodyMap=" + mBodyMap +
  96. '}';
  97. }
  98. }

1、设置参数请求

public void addParams(String key, String value){
    mBodyMap.put(key, value);
}

2、发送请求

public void post(ApiListener listener){
    mApiListener = listener;
    OkHttpUtil.post(getUrl(), mSendListener, mBodyMap);
}
public void postFiles(ApiListener listener, String fileKey, List<File> fileList){
    mApiListener = listener;

    OkHttpUtil.postHasFile(getUrl(),mSendListener,mBodyMap,fileKey,fileList);
}

以登陆接口为例

  1. public class PostLogin extends ApiUtil {
  2. public UserBeans mResponse;
  3. public PostLogin(String userName, String passWord){
  4. addParams("userCode", userName);
  5. addParams("userPassword", passWord);
  6. }
  7. @Override
  8. protected void parseData(JSONObject jsonObject) throws Exception {
  9. mResponse = new Gson().fromJson(jsonObject.optString("data"),UserBeans.class);
  10. }
  11. @Override
  12. protected String getUrl() {
  13. return NetConfig.LOGIN;
  14. }
  15. }

1、可以在初始化时添加参数,或者生成postLogin实例后传参。

2、在getUrl()方法中回调给父类请求URL。 

3、可以在parseData(JSONObject jsonObject)中解析返回的数据,然后定义实体类作为接收:

public UserBeans mResponse;
@Override
protected void parseData(JSONObject jsonObject) throws Exception {
    mResponse = new Gson().fromJson(jsonObject.optString("data"),UserBeans.class);
}

在LoginActivity中调用

  1. private void login() {
  2. if (TextUtils.isEmpty(edtUserName.getText().toString())) {
  3. toShortToast("请输入用户名");
  4. return;
  5. }
  6. if (TextUtils.isEmpty(edtPassword.getText().toString())) {
  7. toShortToast("请输入密码");
  8. return;
  9. }
  10. showLoadingDialog("登录中...");
  11. new PostLogin(edtUserName.getText().toString(), edtPassword.getText().toString()).post(new ApiListener() {
  12. @Override
  13. public void success(ApiUtil apiUtil) {
  14. toShortToast(apiUtil.msg);
  15. PostLogin postLogin = (PostLogin) apiUtil;
  16. SPUtil.put(context, SpKeys.KEY_LOGIN_USER_NAME, edtUserName.getText().toString());
  17. SPUtil.put(context, SpKeys.KEY_USER_ID, postLogin.mResponse.getUserId());
  18. SPUtil.put(context, SpKeys.KEY_USER_TYPE, postLogin.mResponse.getUserType());
  19. if (isRememberPw) {
  20. SPUtil.put(context, SpKeys.KEY_LOGIN_PASSWORD, edtPassword.getText().toString());
  21. } else {
  22. SPUtil.put(context, SpKeys.KEY_LOGIN_PASSWORD, "");
  23. }
  24. Intent intent = new Intent();
  25. intent.setClass(context, MainActivity.class);
  26. context.startActivity(intent);
  27. stopLoadingDialog();
  28. finish();
  29. }
  30. @Override
  31. public void failrure(ApiUtil apiUtil) {
  32. stopLoadingDialog();
  33. toShortToast(apiUtil.msg);
  34. }
  35. });
  36. }

请求监听接口中 success(ApiUtil apiUtil)方法回调 接收的数据

PostLogin postLogin = (PostLogin) apiUtil;

postLogin.mResponse为已经解析好的实体类。

后补:ApiListener 

  1. public interface ApiListener {
  2. //Request success
  3. void success(ApiUtil apiUtil);
  4. //Request failed
  5. void failrure(ApiUtil apiUtil);
  6. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45664
推荐阅读
相关标签
  

闽ICP备14008679号