Java - Http 通讯

news/2025/1/11 20:20:47 标签: java, http, 开发语言
http://www.w3.org/2000/svg" style="display: none;">

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

https://i-blog.csdnimg.cn/direct/0a15fd8c8e9d4d62953e7f740746b71a.png#pic_center" alt="在这里插入图片描述" />

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

http://www.niftyadmin.cn/n/5820125.html

相关文章

OpenBSD之安装指南

安装介质下载 OpenBSD的官网下载地址&#xff1a;https://www.openbsd.org/faq/faq4.html#Download&#xff0c;同时也是《OpenBSD FAQ - Installation Guide》。长篇大论了很多&#xff0c;每一个章节都能看懂是干嘛的&#xff0c;连起来就容易晕。并且是英文的&#xff0c;要…

Linux_进程间通信_共享内存

什么是共享内存&#xff1f; 对于两个进程&#xff0c;通过在内存开辟一块空间&#xff08;操作系统开辟的&#xff09;&#xff0c;进程的虚拟地址通过页表映射到对应的共享内存空间中&#xff0c;进而实现通信&#xff1b;物理内存中的这块空间&#xff0c;就叫做共享内存。…

C/C++ 数据结构与算法【排序】 常见7大排序详细解析【日常学习,考研必备】带图+详细代码

常见7种排序算法 冒泡排序&#xff08;Bubble Sort&#xff09;选择排序&#xff08;Selection Sort&#xff09;插入排序&#xff08;Insertion Sort&#xff09;希尔排序&#xff08;Shell Sort&#xff09;归并排序&#xff08;Merge Sort&#xff09;快速排序&#xff08;…

使用Buildroot开始嵌入式Linux系统之旅-1

文章目录 安装所需要的软件下载buildroot和buildroot-external软件包下载buildroot-mchp下载buildroot-external-microchip 针对目标设备配置buildroot代码buildroot下查看配置执行buildroot编译 buildroot目录下文件夹说明视频教程 Microchip官方Buildroot教程 Microchip官方B…

计算机网络之---静态路由与动态路由

静态路由 静态路由是由网络管理员手动配置并固定的路由方式。路由器通过静态配置的路由条目来转发数据包&#xff0c;而不会自动调整。它不依赖于任何路由协议。 特点&#xff1a; 手动配置&#xff1a;网络管理员需要手动在路由器中配置每条静态路由。不自动更新&#xff1a;…

2025-1-10-sklearn学习(36、37) 数据集转换-无监督降维+随机投影 沙上并禽池上暝。云破月来花弄影。

文章目录 sklearn学习(36、37) 数据集转换-无监督降维随机投影sklearn学习(36) 数据集转换-无监督降维36.1 PCA: 主成份分析36.2 随机投影36.3 特征聚集 sklearn学习(37) 数据集转换-随机投影37.1 Johnson-Lindenstrauss 辅助定理37.2 高斯随机投影37.3 稀疏随机矩阵 sklearn学…

使用 IntelliJ IDEA 创建简单的 Java Web 项目

以下是使用 IntelliJ IDEA 创建几个简单的 Java Web 项目的步骤&#xff0c;每个项目实现基本的登录、注册和查看列表功能&#xff0c;依赖 Servlet/JSP 和基本的 Java Web 开发。 前置准备 确保安装了 IntelliJ IDEA Ultimate&#xff08;社区版不支持 Web 应用&#xff09;。…

【ASP.NET学习】Web Forms创建Web应用

文章目录 什么是 Web Forms&#xff1f;ASP.NET Web Forms - HTML 页面用 ASP.NET 编写的 Hello RUNOOB.COM它是如何工作的&#xff1f;经典 ASP ASP.NET Web Forms - 服务器控件经典 ASP 的局限性ASP.NET - 服务器控件ASP.NET - HTML 服务器控件ASP.NET - Web 服务器控件ASP.N…