当前位置: 首页 > news >正文

HTTP请求

1、get请求工具类

public static String requestGet(String url) throws Exception {
    String strResult = null;
    try {
        HttpClient httpsClient = HttpsClient.getInstance();
        HttpGet request = new HttpGet(url);
        HttpResponse response = httpsClient.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            strResult = EntityUtils.toString(response.getEntity());
            url = URLDecoder.decode(url, "UTF-8");
        } else {
            log.error("httpclientGet通信异常:{}" + url);
        }
    } catch (IOException e) {
        log.error("httpclientGet通信IO异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    } catch (NoSuchAlgorithmException e) {
        log.error("httpclientGet异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    } catch (KeyManagementException e) {
        throw new Exception(e);
    } catch (Exception e) {
        log.error("httpclientGet异常:{}:{}", url, ExceptionMessageHandler.toString(e));
        throw new Exception(e);
    }
    return strResult;
}
2、post请求方式,Content-type为application/json

public static String requestPost(String url, Map<String, Object> params) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 1 创建一个post对象
    HttpPost post = new HttpPost(url);
    post.addHeader("Content-type", "application/json; charset=utf-8");
    post.setHeader("Accept", "application/json");
    // 2 创建一个Entity。模拟一个xml
    StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
    stringEntity.setContentEncoding("UTF-8");
    post.setEntity(stringEntity);
    // 3 执行post请求
    String responseResult = "";
    try {
        CloseableHttpResponse response = httpClient.execute(post);
         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity he = response.getEntity();
        String respContent = EntityUtils.toString(he, "UTF-8");
        responseResult = respContent;
        }
        response.close();
        httpClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseResult;
}
3、post请求方式,Content-type为application/x-www-form-urlencoded

public static String requestXPost(String url, String params, String accessToken) {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 1 创建一个post对象
    HttpPost post = new HttpPost(url);
    //设置请求头,应用监控的请求头权限
    post.addHeader("Authoriz", accessToken);
    post.setHeader("Accept", "application/json, text/plain, */*");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // 添加请求头
    // 2 创建一个Entity。模拟一个xml
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("businessId", params));
    UrlEncodedFormEntity urlEncodedFormEntity = null;
    try {
        urlEncodedFormEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    post.setEntity(urlEncodedFormEntity);
    // 3 执行post请求
    String responseResult = "";
    try {
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity he = response.getEntity();
        String respContent = EntityUtils.toString(he, "UTF-8");
        responseResult = respContent;
        response.close();
        httpClient.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseResult;
}


4 、HttpURLConnection 创建http 请求

public static String sendHttps(String xmlInfo) {
        //String a="";//请求参数
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            trustAllHosts();
            URL realUrl = new URL("https://apitest.bwjf.cn/openNozzle");
 
            //如果是https就是下面两行代码
            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            //如果是http则是下面一行代码
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
           
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //加密
            String base64keyString = encoder(xmlInfo);
            // 发送请求参数
            out.print(base64keyString);
            System.out.println("发送报文:"+xmlInfo);
            System.out.println("加密报文:"+base64keyString);
            // flush输出流的缓冲
            out.flush();
           // System.out.println("响应报文:"+conn.getInputStream());
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
           
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("响应报文:"+result);
            String key = decoder(result);
            System.out.println("响应解密报文:"+key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

http://www.lryc.cn/news/59923.html

相关文章:

  • 网络威胁情报项目:为什么仍然很疯狂
  • Linux系统下使用shell“多线程执行命令”
  • HighTec编译器错误记录
  • 智慧校园大数据云平台(3)
  • 《花雕学AI》15:BingGPT桌面端——尝鲜体验ChatGPT4.0同源技术新Bing的最新成果
  • 反序列化漏洞及PHP魔法函数
  • 企业应用程序单点登录
  • 前馈PID控制(热交换器/反应釜温度控制)
  • Nginx配置ssl证书实现https安全访问
  • 大学生必备神器
  • 【MyBatis Plus】004 -- MyBatis Plus高级(AR、MP插件、自定义全局操作、自动填充、逻辑删除、枚举、代码生成器)
  • 3年外包终上岸,我只能说:但凡有点机会,千万别去外包...
  • 【故障诊断】基于 KPCA 进行降维、故障检测和故障诊断研究(Matlab代码实现)
  • 软件质量保证与软件测试复习笔记(第一周总体介绍+黑盒测试详细)
  • WRF模式与Python融合技术在多领域中的应用及精美绘图教程
  • Reactor设计模式
  • 精通 TensorFlow 2.x 计算机视觉:第二部分
  • 《算法竞赛进阶指南》0x51 线性DP
  • spring数据库事务管理
  • Huggingface微调BART的代码示例:WMT16数据集训练新的标记进行翻译
  • synchronized 的 monitor 机制
  • NumPy 初学者指南中文第三版:1~5
  • ChatGLM-6B论文代码笔记
  • 机器学习入门实例-加州房价预测-1(数据准备与可视化)
  • 【ROS2指南-20】了解ROS2组件的用法
  • 使用AI进行“文本纠错”
  • 第九章 法律责任与法律制裁
  • 如何选择好用的海康视频恢复软件?综合考虑这几点
  • 前端学习:HTML颜色(什么是RGB、HEX、HSL)
  • zookeeper + kafka集群搭建详解