Java - Http 通讯

Java - Http 通讯

PS:
1. Http 协议 POST | GET 请求;
2. 支持 报头、报文、参数 自定义配置;
3. GET 返回支持 String | Stream;
4. 相关依赖:
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4.1</version>
</dependency>
 
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
 </dependency>
 
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>
Demo1: GET
java 复制代码
/**
* Get 请求,仅带参数
*/
RequestHelper.create(IP + URL_TOKEN)
     .params("from_account", ACCOUNT_ID)
     .params("app_key", APP_KEY)
     .params("app_secret", APP_SECRET)
     .getStr(new RequestHelper.NetListener() {
         @Override
         public void onSuccess(String jsonStr) {
             //CommonUtil.printLog(jsonStr);
             JSONObject jsonObject = JSON.parseObject(jsonStr);
             int state = jsonObject.getIntValue("errcode");
             if (state == 0) {
                 U8Token token = jsonObject.getObject("token", U8Token.class);
                 long updateTime = System.currentTimeMillis();
                 CommonUtil.printLog(token.toString());
             } else {
                 CommonUtil.printLog(jsonStr);
             }
         }

         @Override
         public void onError(Throwable e) {
             CommonUtil.printLog(e.getMessage());
         }
     });
Demo 2: POST
java 复制代码
/**
* POST 请求:
* 带 报头、报文;
* 参数放在 报文 内;
*/
baseConnect(url, 1, 1, new RequestHelper.NetListener() {
    @Override
    public void onSuccess(String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        JSONObject data = jsonObject.getJSONObject("std_data");
        if (data == null) {
            CommonUtil.printLog("success: " + jsonStr);
            return;
        }
        JSONObject state = data.getJSONObject("execution");
        String code = state.getString("code");
        if (code.equals("0")) {
            JSONObject parameter = data.getJSONObject("parameter");
            int count = parameter.getIntValue("cnt");
        } else {
            CommonUtil.printLog("error: " + jsonStr);
        }
    }

    @Override
    public void onError(Throwable e) {
        CommonUtil.printLog(e.getMessage());
    }
});

private static void baseConnect(String urlName, int no, int size, RequestHelper.NetListener listener) {
    JSONObject hostObj = new JSONObject();
    hostObj.put("ver", Config.ERP_CONST.HOST_VER);
    hostObj.put("prod", Config.ERP_CONST.HOST_PROD);
    hostObj.put("timezone", "+8");
    hostObj.put("ip", Config.ERP_CONST.SER_IP);
    hostObj.put("id", "");
    hostObj.put("lang", "zh_CN");
    hostObj.put("acct", Config.ERP_CONST.HOST_ACCT);
    hostObj.put("timestamp", getTimeStamp());

    JSONObject serviceObj = new JSONObject();
    serviceObj.put("prod", Config.ERP_CONST.SER_PROD);
    serviceObj.put("ip", Config.ERP_CONST.SER_IP);
    serviceObj.put("name", urlName);
    serviceObj.put("id", Config.ERP_CONST.SER_ID);

    JSONObject paramObj = new JSONObject();
    JSONObject pObj = new JSONObject();
    pObj.put("pageSize", size);
    pObj.put("pageNo", no);
    pObj.put("isGetSchema", false);
    pObj.put("isGetCount", true);
    pObj.put("conditions", new ArrayList<String>());
    pObj.put("orders", new ArrayList<String>());
    paramObj.put("parameter", pObj);

    String key = MD5Encode(hostObj.toJSONString() + serviceObj.toJSONString());
    RequestHelper.create(Config.ERP_CONST.IP)
        .header("digi-key", key)
        .header("digi-host", hostObj.toJSONString())
        .header("digi-service", serviceObj.toJSONString())
        .header("digi-data-exchange-protocol", "1.0")
        .header("Content-Type", "application/json")
        .header("digi-type", "sync")
        .body("std_data", paramObj)
        .postStr(listener);
}
RequestHelper.java
java 复制代码
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Virgo
 * @version 1.0
 * @date 2024/12/18 15:42
 * @usage http post | get 连接请求
 */
public class RequestHelper {
    private final Map<String, Object> mapParam;//paramer 参数
    private Map<String, Object> mapBody;//post -> body 报文
    private Map<String, Object> mapHeader;//head 报头
    private final String url;
    private static PoolingHttpClientConnectionManager manager;//共用连接池

    private RequestHelper(String url) {
        this.url = url;
        mapParam = new HashMap<>();
        init();
    }

    private void init() {
        if (manager == null) {
            manager = new PoolingHttpClientConnectionManager();
            manager.setMaxTotal(10);// 整个连接池最大连接数
            manager.setDefaultMaxPerRoute(5);// 每路由最大连接数,默认值是2
        }
    }

    public static RequestHelper create(String url) {
        return new RequestHelper(url);
    }

    public RequestHelper header(String key, Object value) {
        if (mapHeader == null) {
            mapHeader = new HashMap<>();
        }
        mapHeader.put(key, value);
        return this;
    }

    public RequestHelper header(Map<String, Object> map) {
        if (map == null) {
            return this;
        }
        if (mapHeader == null) {
            mapHeader = new HashMap<>();
        }
        mapHeader.putAll(map);
        return this;
    }

    public RequestHelper body(String key, Object value) {
        if (mapBody == null) {
            mapBody = new HashMap<>();
        }
        mapBody.put(key, value);
        return this;
    }

    public RequestHelper body(Map<String, Object> map) {
        if (map == null) {
            return this;
        }
        if (mapBody == null) {
            mapBody = new HashMap<>();
        }
        mapBody.putAll(map);
        return this;
    }

    public RequestHelper params(Map<String, Object> map) {
        if (map == null) {
            return this;
        }
        mapParam.putAll(map);
        return this;
    }

    public RequestHelper params(String key, Object value) {
        mapParam.put(key, value);
        return this;
    }

    /**
     * post 请求
     *
     * @param listener 回调
     */
    public void postStr(final NetListener listener) {
//        HttpPost post = new HttpPost(parseParam(url));
        HttpPost post;
        try {
            post = new HttpPost(parseParam2(url));
//            CommonUtil.printLog("url: " + post.getURI().toString());
        } catch (URISyntaxException e) {
            if (listener != null) {
                listener.onError(e);
            }
            return;
        }

        //header
        if (mapHeader != null && mapHeader.size() > 0) {
            for (Map.Entry<String, Object> next : mapHeader.entrySet()) {
                post.addHeader(next.getKey(), String.valueOf(next.getValue()));
//                CommonUtil.printLog(next.getKey()+ ":" + next.getValue());
            }
        }

        //body
        if (mapBody != null && mapBody.size() > 0) {
            JSONObject obj = new JSONObject(mapBody);
//            JSONObject obj = (JSONObject) JSONObject.toJSON(mapBody.get("data"));
            String body = JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue);//保留空值
            StringEntity entity;
            try {
                entity = new StringEntity(body);
                post.setEntity(entity);
            } catch (UnsupportedEncodingException e) {
                if (listener != null) {
                    listener.onError(e);
                }
                return;
            }
//            CommonUtil.printLog("body: " + body);
        }

        getResult(post, listener);
    }

    /**
     * get 请求
     *
     * @param listener 回调 string
     */
    public void getStr(final NetListener listener) {
        HttpGet get;
        try {
            get = new HttpGet(parseParam2(url));
        } catch (URISyntaxException e) {
            if (listener != null) {
                listener.onError(e);
            }
            return;
        }

        //header
        if (mapHeader != null && mapHeader.size() > 0) {
            for (Map.Entry<String, Object> next : mapHeader.entrySet()) {
                get.addHeader(next.getKey(), String.valueOf(next.getValue()));
            }
        }

        getResult(get, listener);
    }

    /**
     * get 请求
     *
     * @param listener 回调 stream
     */
    public void getStream(NetFileListener listener) {
        HttpGet get;
        try {
            get = new HttpGet(parseParam2(url));
        } catch (URISyntaxException e) {
            if (listener != null) {
                listener.onError(e);
            }
            return;
        }

        if (mapHeader != null && mapHeader.size() > 0) {
            for (Map.Entry<String, Object> next : mapHeader.entrySet()) {
                get.addHeader(next.getKey(), String.valueOf(next.getValue()));
            }
        }

        getResultStream(get, listener);
    }

    /**
     * 自定义 请求转换参数
     *
     * @param url url
     * @return 转换后url
     */
    private String parseParam(String url) {
        //参数
        if (mapParam.size() > 0) {
            StringBuilder builder = new StringBuilder(url);
            boolean isFirst;
            isFirst = !url.contains("?");

            for (Map.Entry<String, Object> next : mapParam.entrySet()) {
                if (isFirst) {
                    builder.append("?");
                } else {
                    builder.append("&");
                }
                isFirst = false;
                builder.append(next.getKey())
                        .append("=")
                        .append(next.getValue());
            }
            return builder.toString();
        } else {
            return url;
        }
    }

    /**
     * 请求转换参数
     *
     * @param url url
     * @return URI
     * @throws URISyntaxException e
     */
    private URI parseParam2(String url) throws URISyntaxException {
        URIBuilder ub = new URIBuilder();
        ub.setPath(url);

        //参数
        if (mapParam.size() > 0) {
            ArrayList<NameValuePair> pairs = covertParams2NVPS(mapParam);
            ub.setParameters(pairs);
        }
        return ub.build();
    }

    //格式化参数
    private ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }

        return pairs;
    }

    /**
     * 处理Http请求
     */
    private void getResult(HttpRequestBase request, NetListener listener) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(manager).build();
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                response.close();
                if (listener != null) {
                    listener.onSuccess(result);
                }
            }
        } catch (IOException e) {
            if (listener != null) {
                listener.onError(e);
            }
        }
    }

    private void getResultStream(HttpRequestBase request, NetFileListener listener) {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(manager).build();
        try {
            CloseableHttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();// -1 表示长度未知
                if (listener != null) {
                    listener.onProgress(len, 0, 0);
                    listener.onSuccess(entity.getContent());
                }
                response.close();
            }
        } catch (IOException e) {
            if (listener != null) {
                listener.onError(e);
            }
        }
    }

    public interface NetListener {
        void onSuccess(String jsonStr);

        void onError(Throwable e);
    }

    public interface NetFileListener {
        void onSuccess(InputStream stream);

        void onError(Throwable e);

        void onProgress(long totalSize, long currentSize, long speed);
    }
}
相关推荐
Q_27437851095 分钟前
django基于Python的电影推荐系统
java·后端·python·django
ZERO空白16 分钟前
spring task使用
java·后端·spring
Bingjia_Hu31 分钟前
使用 Python 的 pyttsx3 库进行文本转语音
开发语言·python·pyttsx3
xiao--xin31 分钟前
LeetCode100之括号生成(22)--Java
java·开发语言·算法·leetcode·回溯
java1234_小锋34 分钟前
Redis是单线程还是多线程?
java·数据库·redis
sun_weitao37 分钟前
Flutter路由动画Hero函数的使用
java·服务器·flutter
雾里看山41 分钟前
C语言之结构体
c语言·开发语言·笔记
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS企业级工位管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
百流1 小时前
scala基础学习(数据类型)-集合
开发语言·学习·scala
旧物有情1 小时前
蓝桥杯历届真题 # 封闭图形个数(C++,Java)
java·c++·蓝桥杯