关于android:AndroidAndroid-封装-Http-请求工具

工具类

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);
     }
  });

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理