使用httpclient发送https+ip调用

该博客介绍了如何在Java中将HTTP上传请求转换为HTTPS,以满足调用方的安全要求。通过创建自定义的SSL客户端,实现了信任所有证书的SSL上下文,并配置了HTTPS连接管理器。示例代码展示了具体的实现过程,包括上传文件的HTTPPut请求和异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目需求,向指定ip上传文件,刚开始http上传,没有任何问题,后来被调用方要求使用https调用,即向指定ip发送https请求。

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @since 2021/11/30 11:20
 */
public class SSLClient extends DefaultHttpClient {
    public SSLClient() throws Exception {
        super();
        SSLContext ctx = SSLContext.getInstance("SSL");
        X509TrustManager tm = new 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 new X509Certificate[]{};
            }
        };

        ctx.init(null, new TrustManager[]{tm}, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }

}
public boolean upload(String fileid, int index, String cryptSliceHash, int cryptSliceSize, int offset, byte[] data, String ip) {
        log.debug("开始上传");
        StringBuilder url = new StringBuilder("https://")
                .append(ip).append("/dc/upload/v1.0")
                .append("?")
                .append("fileId=").append(fileid).append("&")
                .append("index=").append(index).append("&")
                .append("cryptSliceHash=").append(cryptSliceHash).append("&")
                .append("cryptSliceSize=").append(cryptSliceSize).append("&")
                .append("offset=").append(offset);
        log.debug("上传url=" + url.toString());
        CloseableHttpClient httpclient = null;
        try {
            try {
                httpclient = new SSLClient();
            } catch (Exception e) {
                e.printStackTrace();
                throw new OSSClientException(e.getMessage());
            }
            HttpPut httpPut = new HttpPut(url.toString());
            httpPut.setHeader("X-Auth-Token", this.authToken);
            InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data, offset, cryptSliceSize - offset),
                    cryptSliceSize - offset, ContentType.APPLICATION_OCTET_STREAM);
            httpPut.setEntity(reqEntity);
            try (CloseableHttpResponse response = httpclient.execute(httpPut)) {
                if (response.getStatusLine().getStatusCode() == 200) {
                    final InputStream contentStream = response.getEntity().getContent();
                    BufferedInputStream bis = new BufferedInputStream(contentStream);
                    byte[] c = new byte[1024 * 4];
                    int cnt = 0;

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while ((cnt = bis.read(c)) > 0) {
                        out.write(c, 0, cnt);
                    }
                    out.flush();
                    final ResponseBody res = JSONUtil.toBean(out.toString(), ResponseBody.class);
                    log.debug("上传返回:" + JSONUtil.toJsonStr(res));
                    return res.getCode() == 200;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new OSSClientException(e.getMessage());
            }

        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error("upload,关闭httpclient出错,", e);
            }
        }
        return false;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值