美文网首页
【Android】Android 封装 Http 请求工具

【Android】Android 封装 Http 请求工具

作者: 易含 | 来源:发表于2022-01-04 19:58 被阅读0次

工具类

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * http 请求工具
 *
 * @author Tellsea
 * @date 2021-11-24
 */
public class HttpUtils {

    /**
     * get请求封装
     *
     * @param url
     * @param params
     * @param encode
     * @param listener
     */
    public static void getRequest(String url, Map<String, String> params, String encode, OnResponseListener listener) {
        StringBuffer sb = new StringBuffer(url);
        sb.append("?");
        if (params != null && !params.isEmpty()) {
            //增强for遍历循环添加拼接请求内容
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            if (listener != null) {
                try {
                    URL path = new URL(sb.toString());
                    if (path != null) {
                        HttpURLConnection con = (HttpURLConnection) path.openConnection();
                        //设置请求方式
                        con.setRequestMethod("GET");
                        //链接超时3秒
                        con.setConnectTimeout(3000);
                        con.setDoOutput(true);
                        con.setDoInput(true);
                        OutputStream os = con.getOutputStream();
                        os.write(sb.toString().getBytes(encode));
                        os.close();
                        //应答码200表示请求成功
                        if (con.getResponseCode() == 200) {
                            onSuccess(encode, listener, con);
                        }
                    }
                } catch (Exception error) {
                    error.printStackTrace();
                    onError(listener, error);
                }
            }
        }
    }

    /**
     * POST请求
     *
     * @param url
     * @param params
     * @param encode
     * @param listener
     */
    public static void postRequest(String url, Map<String, String> params, String encode, OnResponseListener listener) {
        StringBuffer sb = new StringBuffer();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        if (listener != null) {
            try {
                URL path = new URL(url);
                if (path != null) {
                    HttpURLConnection con = (HttpURLConnection) path.openConnection();
                    con.setRequestMethod("POST");   //设置请求方法POST
                    con.setConnectTimeout(3000);
                    con.setDoOutput(true);
                    con.setDoInput(true);
                    byte[] bytes = sb.toString().getBytes();
                    OutputStream outputStream = con.getOutputStream();
                    outputStream.write(bytes);
                    outputStream.close();
                    if (con.getResponseCode() == 200) {
                        onSuccess(encode, listener, con);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                onError(listener, e);
            }
        }
    }

    private static void onError(OnResponseListener listener, Exception onError) {
        listener.onError(onError.toString());
    }

    private static void onSuccess(String encode, OnResponseListener listener, HttpURLConnection con) throws IOException {
        InputStream inputStream = con.getInputStream();
        //创建内存输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        if (inputStream != null) {
            while ((len = inputStream.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            String str = new String(baos.toByteArray(), encode);
            listener.onSuccess(str);
        }
    }
}
/**
 * 请求回调
 *
 * @author Tellsea
 * @date 2021-11-24
 */
public interface OnResponseListener {

    void onSuccess(String response);

    void onError(String error);
}

使用案例

Map<String, String> map = new HashMap<>();
  map.put("extract", encrypt);
  HttpUtils.getRequest("http://tellsea.4kb.cn/arcFace/arcFace", map, "utf-8", new OnResponseListener() {
     @Override
     public void onSuccess(String response) {
         System.out.println(response);
         AjaxResult result = new Gson().fromJson(response, AjaxResult.class);
         if (IntegerUtils.eq(result.getCode(), 200)) {
             // 处理逻辑业务
         } else {
             // 识别失败
         }
     }

     @Override
     public void onError(String error) {
         System.out.println("请求失败:" + error);
     }
  });

相关文章

网友评论

      本文标题:【Android】Android 封装 Http 请求工具

      本文链接:https://www.haomeiwen.com/subject/kmhccrtx.html