Http 解析url 各种参数类型工具类(文件,json,xml)

2023-05-16

1.http post请求传参数+文件

import java.nio.charset.Charset;
import java.util.*;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;


/**
 * 
 * @Description:
 * @Author:ay
 * @Date:2020/8/26
 */
public class HttpFileUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();
    private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
    /** * 发送HttpPost请求,参数为文件,适用于微信上传素材 * * @param url * 请求地址 * @param file * 上传的文件 * @return 返回字符串 * @throws IOException * @throws ClientProtocolException */
    public static String sendPost(String url, String method,Map<String, Object> paramMap, List<File> files) throws IOException {
        // 20190519 wangwei 修改参数逻辑: 参数级别url,paramMap,attributes,前面已经出现的,后面设置的无效
        // 定义包含的参数
        // 提出原本url里面的参数
        List<String> existParamList = getUrlParam(url);
        StringBuffer params = new StringBuffer();
        // url参数处理
        if (paramMap != null && paramMap.size() > 0) {
            Iterator<Map.Entry<String, Object>> iter = paramMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, Object> entry = iter.next();
                if (!existParamList.contains(entry.getKey())) {
                    params.append(entry.getKey() + "=" + entry.getValue() + "&");
                    existParamList.add(entry.getKey());
                }
            }
        }
        // 获取request自带参数
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> enuer = request.getParameterNames();
            while (enuer.hasMoreElements()) {
                String paraName = (String) enuer.nextElement();
                // 参数(如果需要得统一编码处理)需要编码统一处理,防止特殊字符情况
                if (!existParamList.contains(paraName)) {
                    params.append(paraName + "=" + request.getParameter(paraName) + "&");
                    existParamList.add(paraName);
                }
            }
        }
        // 将request自带参数和url参数拼接在url后面
        if (params.length() > 1) {
            if (url.contains("?")) {
                url = url + "&" + params.deleteCharAt(params.length() - 1);
            } else {
                url = url + "?" + params.deleteCharAt(params.length() - 1);
            }
        }
        String result = null;
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 实例化参数对象
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.setCharset(Charset.forName("utf-8"));

        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //multifile 转file,存file
        for(File file :files){
            multipartEntity.addBinaryBody("files",file);
     //       httpPost.setHeader( "Content-Disposition", "attachment;filename=" + new String( file.getName().getBytes("GBK"), "ISO8859-1" ) );
        }
           httpPost.setEntity(multipartEntity.build());
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            // 关闭CloseableHttpResponse
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
        return result;
    }
    /**
     * 获取url里面参数名称
     *
     * @param url 地址
     * @return 参数名称
     * @author wangwei
     * @date 2019年5月19日
     */
    private static List<String> getUrlParam(String url) {
        // 定义包含的参数
        List<String> existParam = new ArrayList<>();
        // 提出原本url里面的参数
        if (url.contains("?")) {
            String urlParam = url.split("\\?")[1];
            String[] urlParamS = urlParam.split("&");
            for (String up : urlParamS) {
                existParam.add(up.split("=")[0]);
            }
        }
        return existParam;
    }


    public static File MutifileToFile(MultipartFile multipartFile ){
        //文件上传前的名称
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try{
            //获取文件流,以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for(int i = 0; i < ss.length; i++){
                out.write(ss[i]);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


}

2.Http post 传报文格式的数据(JSON格式数据)



/**
 *
 * @Description:
 * @Author:ay
 * @Date:2020/9/5
 */

import java.io.IOException;
        import java.net.URI;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.Map;

        import org.apache.http.NameValuePair;
        import org.apache.http.client.entity.UrlEncodedFormEntity;
        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.utils.URIBuilder;
        import org.apache.http.entity.ContentType;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.impl.client.CloseableHttpClient;
        import org.apache.http.impl.client.HttpClients;
        import org.apache.http.message.BasicNameValuePair;
        import org.apache.http.util.EntityUtils;

public class HttptestUtil {


    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
}

3.post 解析WebService xml 格式数据

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author songwen
 * @Title: WebServiceUtils
 * @Description: TODO
 * @date 2018/8/30
 */
public class WebServiceUtils {

    /**
     * 判断URL是否可达
     *
     * @param url 待判断的URL
     * @return true: 可达 false: 不可达
     */
    public static boolean urlIsReach(String url) {
        if (url == null) {
            return false;
        }
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    public static boolean urlIsReach(String url, int receiveTimeOut, int connectTimeOut) {
        if (url == null) {
            return false;
        }
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(receiveTimeOut);
            connection.setConnectTimeout(connectTimeOut);
            if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * 请求webservice服务
     *
     * @param url    地址
     * @param method 方法名
     * @param map    参数
     * @return
     * @throws Exception
     */
    public static String sendRequest(String url, String method, Map<String, Object> map) throws Exception {
        return sendRequest(url, method, null, null, map.values().toArray());
    }

    /**
     * 请求webservice服务
     *
     * @param url    地址
     * @param method 方法名
     * @param map    参数
     * @return
     * @throws Exception
     */
    public static String sendRequest(String url, String method, Long connectTimeOut, Long receiveTimeOut, Map<String, Object> map) throws Exception {
        return sendRequest(url, method, connectTimeOut, receiveTimeOut, map.values().toArray());
    }

    /**
     * 请求webservice服务
     *
     * @param url            地址
     * @param method         方法名
     * @param connectTimeOut 连接超时时间
     * @param receiveTimeOut 接收超时时间
     * @param params         参数
     * @return
     * @throws Exception
     */
    public static String sendRequest(String url, String method, Long connectTimeOut, Long receiveTimeOut, Object... params) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(url);
        HTTPClientPolicy policy = new HTTPClientPolicy();
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        if (connectTimeOut != null) {
            policy.setConnectionTimeout(connectTimeOut);
        }
        if (receiveTimeOut != null) {
            policy.setReceiveTimeout(receiveTimeOut);
        }
        conduit.setClient(policy);
//        Object[] invoke = client.invoke(method, params);
        Object[] objects = client.invoke(method, params);
        String result =  GsonUtils.beanTojson(objects[0]);
      //  System.out.println(GsonUtils.beanTojson(objects[0]));

      //  client.close();
        return result;
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Http 解析url 各种参数类型工具类(文件,json,xml) 的相关文章

  • 【Linux问题解决】操作系统用C语言多线程编程 对‘pthread_create’未定义的引用 报错解决办法

    操作系统用C语言多线程编程 对 pthread create 未定义的引用 报错解决办法 今天写操作系统作业 在Ubuntu Linux系统中用C语言编写多线程程序 在命令行进行编译 没通过编译 报错如下 xff1a In file inc
  • linux 服务器执行post请求 curl命令详解

    什么是curl xff1f curl是一个命令行访问URL的计算机逻辑语言的工具 xff0c 发出网络请求 xff0c 然后得到数据并提取出 xff0c 显示在标准输出 stdout 上面 xff0c 可以用它来构造http request
  • open-falcon 监控cpu指标及含义

    user 30512019 从系统启动开始累计到当前时刻 xff0c 用户态的CPU时间 xff0c 不包含nice值为负进程 nice 2905 从系统启动开始累计到当前时刻 xff0c nice值为负的进程所占用的CPU时间 syste
  • [Unity] 串口读取数据错误 IOException: 拒绝访问。

    错误内容 IOException 拒绝访问 System IO Ports WinSerialStream ReportIOError System String optional arg at lt 14e3453b740b4bd690e
  • px4仿真无法起飞问题(Failsafe enabled: no datalink)

    报错信息 问题描述 xff1a 使用JMAVSim和gazebo仿真px4起飞时报错如下 xff1a WARN commander Failsafe enabled no datalink 说不安全 解决方法 打开QGC 就可以起飞了
  • TCP (传输控制协议)和 UDP

    传输控制协议 xff08 TCP xff0c Transmission Control Protocol xff09 是一种面向连接的 可靠的 基于字节流的传输层通信协议 是为了在不可靠的互联网络上提供可靠的端到端字节流而专门设计的一个传输
  • 全网第一篇 Jetson AGX Xaiver + Jetpack5.0.2(Ubuntu20.04) + ROS2 + ORB-SLAM3 + ZED2

    本机系统 xff1a Jetpack5 0 2 Ubuntu 20 04 LTS 注意事项 xff1a 想要避坑 xff0c 务必按照文中版本准备各种环境 一 安装软件 1 Pangolin 0 5 网址 xff1a https githu
  • java中char转化为int的几种方法

    java中char转化为int的几种方法总结 方法一 xff1a 在char后面 0 span class token keyword public span span class token keyword class span span
  • 大疆 RoboMaster 3508/2006/GM6020 电机使用教程

    19年开始使用大疆的电机 xff0c 刚开始接触有很多东西不懂 xff0c 网上除了RM官网提供的一些资料外没有很多其他的资料 xff0c 现在使用大疆电机近一年了 xff0c 想分享一下自己的经验 1 硬件部分 1 C610电调只能连接M
  • DBC文件解析及CAN通信矩阵

    一般的 DBC 文件中包含了如下的8种信息 xff1a 1 版本与新符号 2 波特率定义 3 网络节点的定义 4 报文帧的定义 5 信号的定义 6 注解部分 7 特征部分 8 数值表部分 VERSOIN 34 34 版本信息 xff0c 为
  • 基于Rplidar二维雷达使用Hector_SLAM算法在ROS中建图

    文章目录 前言一 ROS分布式通信 xff08 配置多机通信 xff09 1 简介2 步骤2 1 准备2 2 修改配置文件2 3配置主机IP2 4配置从机IP 二 RPlidar的使用教程1 创建环境2 下载激光雷达的功能包3 编译4 启动
  • TCP连接建立的步骤

    TCP连接建立的步骤 一 客户端向服务器端发送连接请求后 xff0c 就被动地等待服务器的响应 典型的TCP客户端要经过下面三步操作 xff1a 1 创建一个Socket实例 xff1a 构造函数向指定的远程主机和端口建立一个TCP连接 x
  • 能否在头文件中放置函数定义?

    语法上是可以这样做的 xff0c 但是在编程规范中并不鼓励这样做 成员函数一般是不可以在头文件中定义的 xff0c 只能在头文件中声明 因为函数只能有一次定义 xff0c 而可以有多次声明 xff0c 当头文件被多次包含的时候 xff0c
  • 万能的sprintf

    0 前言 先推荐一本书 xff0c 政治书籍 政治的人生 xff0c 算是一本日记题材 是现任 xff0c 作者大家百度一下就知道了 xff0c 这里不宜过多说明 从这本书里 xff0c 可以看出来现在的社会 这本书是30年前的 大佬就是大
  • 串口通讯UART/RS232/RS485/RS-422笔记

    串口通讯详解笔记 串口通讯概述串口通讯传输数据帧的结构UARTRS232RS485RS 422RS 232 RS 422和RS 485的主要区别 xff08 重要 xff09 串口通讯概述 串口通讯是指数据按位 xff08 bit xff0
  • Stm32 hal库 usart2与hc-08透传模块通讯

    Stm32 hal库 usart2与hc 08透传模块通讯 xff08 附数据解析 xff09 一 stm32cubeMX配置 1 配置RCC为外部晶振 2 配置时钟树 3 配置usart1 usart2 xff0c 其中usart1将作为
  • darknet分类网络,训练,C++调用分类器

    Darknet 分类器 出于对Darknet框架下YOLO结构的火热 xff0c 网络上一堆关于目标检测的C 43 43 调用形式和模板 xff0c 但是未曾存在C 43 43 调用分类器的模板 xff0c 故采用如下形式 xff0c 展开
  • zed2 win10 采集数据

    环境 xff1a win10 cuda10 2 zed2相机 zed sdk 3 7 python3 7 1 标定 参考的博客 2 配置环境 1 xff09 win10安装cuda cudnn 如何查看windows的cuda版本 win1
  • 链表指针赋值

    总结来说 xff0c 就是等号赋值右边的指针 xff08 节点地址 xff09 不变 xff0c 左边的地址变成右边的 即左边的指针移到右边指针的位置 xff08 PS 指针命名时不要用next xff0c 会搞混 xff09 span c
  • 网络基础知识和常用数据帧格式

    网络基础知识和常用数据帧格式 1 IP路由相关1 1 网络分层1 2 网络分段1 3 子网掩码1 4 网关功能1 5 数据路由 2 常用帧格式2 1 ARP帧格式2 2 ICMP帧格式2 3 UDP帧格式2 4 TCP帧格式 本文主要介绍网

随机推荐