okhttp网络请求工具

发布时间:2024年01月04日

?先依赖

implementation 'com.squareup.okhttp3:logging-interceptor:3.5.0'
implementation 'com.google.code.gson:gson:2.8.0'

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;

import com.artvrpro.yiwei.MyApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
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;

/**
 * 
 *okhttp网络请求工具
 * 
 * 
 */
public class HttpUtils {

    private static OkHttpClient client = null;

    private HttpUtils() {
    }

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (HttpUtils.class) {
                if (client == null)
                    client = new OkHttpClient().newBuilder()
                            .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间  AI生图时长超过10秒,不设置会访问失败,timeout
                            .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                            .build();;
            }
        }
        return client;
    }

    /**
     * 判断网络
     *
     * @param context
     * @return
     */
    public static int isConnNetWork(Context context) {

        ConnectivityManager conManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null) {
            if (!conManager.getActiveNetworkInfo().isAvailable()) {
                return 1;
            }
            if (conManager.getActiveNetworkInfo().isConnected()) {
                return 3;
            }
            if (conManager.getActiveNetworkInfo().isConnectedOrConnecting()) {
                return 2;
            }
        }
        return 1;
    }

    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url, Callback callback) {
        Log.e("ceshia", isConnNetWork(MyApplication.mContext) + "--------------");
        if (1 != isConnNetWork(MyApplication.mContext)) {
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("x-shinemi-auth", SPUtils.get("token","")+"")
                    .build();
            Call call = getInstance().newCall(request);
            call.enqueue(callback);
        } else {
            Toast.makeText(MyApplication.mContext, "网络断开,请打开网络", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void doPost(String url, Map<String, String> mapParams, Callback callback) {
        if (1 != isConnNetWork(MyApplication.mContext)) {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : mapParams.keySet()) {
                builder.add(key, mapParams.get(key));
            }
            Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();
            Call call = getInstance().newCall(request);
            call.enqueue(callback);
        } else {
            Toast.makeText(MyApplication.mContext, "网络断开,请打开网络", Toast.LENGTH_SHORT).show();
        }
    }
/*
*//**
     * 表单,上传图片
     *//*
    public static void doFileKey(String key, File cropFile, Callback callback){
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(key, IMAGE_FILE_NAME_TEMP,
                        RequestBody.create(MEDIA_TYPE_PNG,cropFile ))
                .build();

        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "9199fdef135c122")
                .url("http://monan.antiphon168.com/Doctor/Index/uploadThumbImage?")
                .post(requestBody)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }*/

    /**
     * Post请求发送JSON数据
     *
     * @param url
     * @param jsonParams
     * @param callback
     */
    public static void doPost(String url, String jsonParams, Callback callback) {
        if (1 != isConnNetWork(MyApplication.mContext)) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("x-shinemi-auth", SPUtils.get("token","")+"")
                .post(body)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
        } else {
            Toast.makeText(MyApplication.mContext, "网络断开,请打开网络", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上传文件
     *
     * @param url
     * @param pathName
     * @param fileName
     * @param callback
     */
    public static void doFile(String url, String pathName, String fileName, Callback callback) {
        //判断文件类型
        MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
        //创建文件参数
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(MEDIA_TYPE.type(), fileName,
                        RequestBody.create(MEDIA_TYPE, new File(pathName)));
        //发出请求参数
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "9199fdef135c122")
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);

    }

    /**
     * Post上传图片的参数
     *
     * @param BodyParams
     * @param fileParams
     * @return
     */
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public static RequestBody SetFileRequestBody(Map<String, String> BodyParams, Map<String, String> filePathParams) {
        // 带文件的Post参数
        RequestBody body = null;
        MultipartBody.Builder MultipartBodyBuilder = new MultipartBody.Builder();
        MultipartBodyBuilder.setType(MultipartBody.FORM);
        RequestBody fileBody = null;
        if (BodyParams != null) {
            Iterator<String> iterator = BodyParams.keySet().iterator();
            String key = "";
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                MultipartBodyBuilder.addFormDataPart(key, BodyParams.get(key));
            }
        }
        if (filePathParams != null) {
            Iterator<String> iterator = filePathParams.keySet().iterator();
            String key = "";
            int i = 0;
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                i++;
                MultipartBodyBuilder.addFormDataPart(key, filePathParams.get(key));
                fileBody = RequestBody.create(MEDIA_TYPE_PNG, new File(filePathParams.get(key)));
                MultipartBodyBuilder.addFormDataPart(key, i + ".png", fileBody);
            }
        }
        body = MultipartBodyBuilder.build();
        Log.e("bodybodybodee", body + "");
        return body;
    }


    /**
     * 根据文件路径判断MediaType
     *
     * @param path
     * @return
     */
    private static String judgeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 下载文件
     *
     * @param url
     * @param fileDir
     * @param fileName
     */
    public static void downFile(String url, final String fileDir, final String fileName) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(fileDir, fileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }
        });
    }
}

使用方法:

post请求:

 final Gson gson = new Gson();
 String jsontype = gson.toJson(dataBean);    //把数据实体类转成json字符串

  HttpUtils.doPost("接口地址", jsontype, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("AiCreativityPicBean", e.toString() + "----------");
                
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String info = response.body().string();
                Log.d("AiCreativityPicBean", info + "----------");
                aiCreativityPicBeanResponse = gson.fromJson(info, AiCreativityPicBeanResponse.class);
               




            }
        });
    }

get请求:

   HttpUtils.doGet("请求接口", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                 Log.d("AiCreativityPicBean", e.toString() + "----------");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
  String info = response.body().string();
                Log.d("AiCreativityPicBean", info + "----------");
                aiCreativityPicBeanResponse = gson.fromJson(info, AiCreativityPicBeanResponse.class);
                
            }
        });

序列化工具:

import com.google.gson.Gson;

public class GsonUtil {

    private static Gson mGson = new Gson();

    /**
     * 序列化
     * @param json  json字符串
     * @param classOfT 实体类
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Object toObject(String json, Class classOfT) {
        return mGson.fromJson(json, classOfT);
    }

    /**
     * 反序列化
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String toJson(T object) {
        return mGson.toJson(object);
    }


}

使用:

ExhibitionWorkDetailsBean exhibitionWorkDetailsBean = (ExhibitionWorkDetailsBean) GsonUtil.toObject(resultJson/*json字符串*/,ExhibitionWorkDetailsBean.class);
          
文章来源:https://blog.csdn.net/qq_38306233/article/details/135389863
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。