HttpClient调用二进制图片接口处理并把图片响应前端

欢迎使用Markdown编辑器

  • HttpClient调用二进制图片接口处理并把图片响应前端
    • 遇到的问题
      • 1、SSLPeerUnverifiedException异常
      • 解决方法
    • 具体代码附上

HttpClient调用二进制图片接口处理并把图片响应前端

这篇博客用来记录工作中调用 获取二进制图片的接口 处理方式。如果你也在工作中遇到此类问题,可以当作参考,当然也可以提出问题一起交流。

遇到的问题

用HttpClient发送HTTPS请求报异常:Exception in thread “main” javax.net.ssl.SSLPeerUnverifiedException: Certificate for doesn’t match any of the subject alternative names: [域名]

1、SSLPeerUnverifiedException异常

一般出此类问题是配置的https证书有问题,在网页上访问https://xxx.id一般出现您的连接不是私密连接如下图所示,可以确定是https证书配置有问题;联系相关人员(一般是公司的运维同学负责)配置好证书就行了。
HttpClient调用二进制图片接口处理并把图片响应前端_第1张图片

解决方法

			//javax.net.ssl.SSLPeerUnverifiedException解决方法
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE
            );
            //HttpClient httpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler())..build();
            HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build();

具体代码附上

 public void getPQFReport(String ymlx, String ymph, HttpServletRequest request, HttpServletResponse response) {

        //获取接口url
        String url = "https://xxxx.xx";
        HttpPost httppost = new HttpPost(url);
        //传递参数
        List params = new ArrayList();
        params.add(new BasicNameValuePair("ymlx", ymlx));
        params.add(new BasicNameValuePair("ymph", ymph));
        HttpResponse httpResponse = null;
        HttpEntity httpEntity = null;
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            //设置连接超时时间
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            httppost.setConfig(requestConfig);
            //javax.net.ssl.SSLPeerUnverifiedException解决方法
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE
            );
            //HttpClient httpclient = HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler())..build();
            HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(scsf).build();
            httpResponse = httpclient.execute(httppost);
        } catch (Exception e1) {
            System.out.println("----------------失败");
        }
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 请求正常
            try {
                httpEntity = httpResponse.getEntity();
                BufferedInputStream br = new BufferedInputStream(httpEntity.getContent());
                byte[] buf = new byte[1024];
                int len = 0;
                response.reset();
                response.setContentType("image/jpg");
                String fileName = "report.jpg";
                try {
                    String initPath = httpResponse.getAllHeaders()[0].getValue().split(";")[1].split("=")[1];
                    //获取路径
                    //String filePath = initPath.substring(0, initPath.lastIndexOf("/") + 1);
                    //获取文件名
                    fileName = initPath.substring(initPath.lastIndexOf("/") + 1, initPath.length() - 1);
                } catch (Exception e) {
                }
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                OutputStream out = response.getOutputStream();
                while ((len = br.read(buf)) != -1)
                    out.write(buf, 0, len);

                br.close();
                out.flush();
            } catch (Exception e) {
                System.out.println("解析失败");
            }
        } else {
            System.out.println("调用失败");
        }
    }

如果需要文件上传,则通过httpEntity.getContent()去取inputStream流,上传到文件存储就可以了。如果有问题,欢迎提问!

你可能感兴趣的:(httpClient,调用图片接口,响应前端图片内容,java)