首页 > 其他分享 >http请求方式-HttpURLConnection

http请求方式-HttpURLConnection

时间:2022-10-13 19:24:42浏览次数:40  
标签:http 请求 connection br import new null HttpURLConnection String

http请求方式-HttpURLConnection

import com.alibaba.fastjson.JSON;
import com.example.core.mydemo.http.OrderReqVO;
import org.springframework.lang.Nullable;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpURLConnectionUtil {
    /*
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }

    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, @Nullable String param) throws Exception{
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
//            connection = (HttpURLConnection) url.openConnection();
            if(httpUrl.startsWith("https")){
                trustHttps();
                connection = (HttpsURLConnection) url.openConnection();
            }else{
                connection = (HttpURLConnection) url.openConnection();
            }
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //拼装参数
            if (null != param && !param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }


    private static void trustHttps() throws Exception{
        //第一个参数为协议,第二个参数为提供者(可以缺省)
        SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
        TrustManager[] tm = {new MyX509TrustManager()};
        sslcontext.init(null, tm, new SecureRandom());
        HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslsession) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
    }

    public static class MyX509TrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    }

    public static void main(String[] args) {
        OrderReqVO data = new OrderReqVO();
        data.setOrderNum("111123333");
        data.setServerType("1");


        String url = "https://域名/接口名称";

        String message = null;
        try {
            message = doPost(url, JSON.toJSONString(data));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("message = " + message);
    }

}

 

标签:http,请求,connection,br,import,new,null,HttpURLConnection,String
From: https://www.cnblogs.com/oktokeep/p/16789352.html

相关文章

  • scrapy 给单个请求设置超时时间
       meta={'download_timeout':30}     ......
  • http 报文
    一、报文格式:一个HTTP请求报文由请求行(requestline)、请求头部(header)、空行和请求数据4个部分组成,具体格式如下;1.请求报文格式起始行<method>      空格   <r......
  • uni-app发送GET和POST请求方式
    基于上一篇文章对AJAX概念的描述,那么目前流行的uni-app到底是怎么发请求的呢,我会把格式写在下面使用uni.request()发起GET请求:使用uni.request()发起POST请求let......
  • python requests库提示警告:InsecureRequestWarning: Unverified HTTPS request is bei
    在利用requests访问链接,有时有有警告InsecureRequestWarning:UnverifiedHTTPSrequestisbeingmade.Addingcertificatever解决办法:Python3访问HT......
  • watch 监视搜索关键词的变化不断发送请求返回建议
    watch:{keywords:{//yarnaddlodash下载lodash包//import{debounce}from"lodash";引入防抖的函数//每隔700ms执行一次handler......
  • 【HTTP】190-http 状态码竟然可以这样记
    标题皮了一下,但是内容应该算是比较用心的,不是直接抄了一下官方文档和一堆抽象的术语,尽量配合实例解释的通俗一些。基本介绍状态码(StatusCode)和原因短语(ReasonPhrase)用于简......
  • 下载https图片工具类
    普通http工具类httpClient访问https图片会报以下错误javax.net.ssl.SSLHandshakeException:java.security.cert.CertificateException:Nosubjectalternativenames......
  • 45. JS Ajax请求(简明教程)
    1.前言Ajax全称“AsynchronousJavaScriptandXML”,译为“异步JavaScript和XML”,程序员们习惯称之为“阿贾克斯”,它并不是一种技术,而是多种技术的综合体,其中包括Ja......
  • nginx访问控制,用户认证,配置https,zabbix监控nginx状态页面
    nginx访问控制,用户认证,配置https,zabbix监控nginx状态页面nginx访问控制用于location段allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开deny:设定禁止哪台或哪些......
  • 前端get请求怎么携带token
    有时候,get请求也需要携带token怎么办,比如请求借口到处excel数据,后端是通过当前用户信息进行校验的,普通的window.open又不方便携带请求头等信息此时就需要额外的处理了这......