http和https连接下载

给一个可以下载的http地址和https地址,分别用不同的方式来下载,https需要SSL证书,
另外呢,http和https如何转换? 不要用https来访问http 
解决了蛮久的,最后发现是网络原因,外网连接不上,所以联调的时候,用内网和外网分别请求,先排除网络原因.
(为啥没想到断开网络用外网连接请求呢?感觉思路啊,还是得多训练这种思维和处理问题的方式)

/**
 * 获取网络图片流
 *
 * @param url
 * @return
 */
public static byte[] getNetWorkStream(String url) {
    HttpURLConnection connection=null;
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            byte[] bytes= IOUtils.toByteArray(inputStream);
            inputStream.close();
            return bytes;
        }
    } catch (IOException e) {
        log.error("获取网络图片出现异常,图片路径为:" ,e);
    }finally {
        if(connection!=null){
            connection.disconnect();
        }
    }
    return null;
}



/**
 * 获取网络图片流头部的文件名后缀
 * resultMap: key[fileName、bytes]
 * @param url
 * @return
 */
public static Map<String,Object> getNetWorkStreamAndFileName(String url) {
    HttpURLConnection connection=null;
    int responseCode = -100 ;
    Map resultMap = new HashMap();
    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        responseCode = connection.getResponseCode() ;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String  fileName = connection.getHeaderField("Content-Disposition");
            if(fileName != null){
                fileName = new String(fileName.getBytes("ISO-8859-1"),"GBK").split("=")[1];
            }
            InputStream inputStream = connection.getInputStream();
            byte[] bytes= IOUtils.toByteArray(inputStream);
            if(StringUtils.isEmpty(fileName)){
                fileName=url.substring(url.lastIndexOf("/")+1);
            }
            resultMap.put("fileName",fileName);
            resultMap.put("bytes",bytes);
            inputStream.close();
            return resultMap;
        }
    } catch (IOException e) {
        log.error("获取网络文件出现异常,网络路径为:" ,e);
    }finally {
        log.info("请求连接的返回的响应码ResponseCode:"+responseCode);
        if(connection!=null){
            connection.disconnect();
        }
    }
    return null;
}

/**
 * 获取网络图片流
 *
 * @param url
 * @return
 */
public static byte[] getNetWorkStreamHttps(String url) throws IOException, NoSuchProviderException, NoSuchAlgorithmException {
    SSLContext sslcontext = SSLContext.getInstance("SSL","SunJSSE");
    try {
        sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };
    URL myURL = new URL(url);
    // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
    HttpsURLConnection connection = (HttpsURLConnection) myURL.openConnection();
    connection.setSSLSocketFactory(sslcontext.getSocketFactory());
    connection.setHostnameVerifier(ignoreHostnameVerifier);
    try {
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            byte[] bytes= IOUtils.toByteArray(inputStream);
            inputStream.close();
            return bytes;
        }
    } catch (IOException e) {
        log.error("获取网络图片出现异常,图片路径为:" ,e);
    }finally {
        if(connection!=null){
            connection.disconnect();
        }
    }
    return null;
}

/**
 * 获取网络图片流头部的文件名后缀
 * resultMap: key[fileName、bytes]
 * @param url
 * @return
 */
public static Map<String,Object> getNetWorkStreamAndUrlFileName(String url) throws IOException, NoSuchProviderException, NoSuchAlgorithmException {
    SSLContext sslcontext = SSLContext.getInstance("SSL","SunJSSE");
    try {
        sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };
    URL myURL = new URL(url);
    // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
    HttpsURLConnection connection = (HttpsURLConnection) myURL.openConnection();
    connection.setSSLSocketFactory(sslcontext.getSocketFactory());
    connection.setHostnameVerifier(ignoreHostnameVerifier);
    //之后任何Https协议网站皆能正常访问,同第一种情况
    //HttpURLConnection connection=null;
    int responseCode = -100 ;
    Map resultMap = new HashMap();
    try {
        //connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod("GET");
        responseCode = connection.getResponseCode() ;
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String  fileName = connection.getHeaderField("Content-Disposition");
            if(fileName != null){
                fileName = new String(fileName.getBytes("ISO-8859-1"),"GBK").split("=")[1];
            }
            InputStream inputStream = connection.getInputStream();
            byte[] bytes= IOUtils.toByteArray(inputStream);
            if(StringUtils.isEmpty(fileName)){
                fileName=url.substring(url.lastIndexOf("/")+1);
            }
            resultMap.put("fileName",fileName);
            resultMap.put("bytes",bytes);
            inputStream.close();
            return resultMap;
        }
    } catch (IOException e) {
        log.error("获取网络文件出现异常,网络路径为:" ,e);
    }finally {
        log.info("请求连接的返回的响应码ResponseCode:"+responseCode);
        if(connection!=null){
            connection.disconnect();
        }
    }
    return null;
}


public static void main(String[] args) throws NoSuchProviderException, NoSuchAlgorithmException, IOException {
    String url = "";
    byte[] a = CommonUtils.getNetWorkStreamHttps(url);
    System.out.println(a);
}


public class MyX509TrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate certificates[],String authType) throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] ax509certificate,String s) throws CertificateException {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }
}

还是连接超时,最后找到问题根源是因为信息安全做了域名限制策略,只能用域名访问而不能用ip,但是银行方用的是ip访问所以连接不上

这种问题要找到运维和信息安全处理,了解行方访问方式是用ip的,

通过断开网络和连接网络来反复测试,telnet ip 端口不行,telnet 域名 端口可以,

ok 解决了~

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值