企业微信上传临时素材文件

1.控制层

    /**
     * 上传临时素材
     */
    @ResponseBody
    @PostMapping("/uploadResource")
    public BaseResponse uploadResource(MultipartHttpServletRequest param,@RequestParam("accessToken") String token,@RequestParam("type")String type) throws Exception{
        return BaseResponse.Builder.build(weixinService.uploadResource(param,token,type));
    }

2.Service层

    /**
     * 上传临时素材
     * @param param
     * @return
     */
    Map uploadResource(MultipartHttpServletRequest param,String accessToken,String type)throws Exception ;

3.实现层

    @Override
    public Map uploadResource(MultipartHttpServletRequest param,String accessToken,String type)throws Exception  {
        /**
         * 1.封装Multipart参数
         */
        MultipartFile file = param.getFile("file");

        /**
         * 2.调用上传临时素材接口
         */
        String result = uploadFile(M2F(file), type, accessToken);
        log.info("getMessageResult result=" + result);

        /**
         * 3.返回上传临时素材接口响应数据
         */
        Map map=new HashMap<>();
        JSONObject resultObject = new JSONObject(result);
        map.put("errcode",resultObject.getInt("errcode"));
        map.put("errmsg",resultObject.get("errmsg"));
        map.put("media_id",resultObject.get("media_id"));
        return map;
    }

   /**
     * MultipartFile文件转File文件
     * @param file
     * @return
     * @throws Exception
     */
    public File M2F(MultipartFile file) throws Exception {
        File f=File.createTempFile(UUID.randomUUID().toString(), "." + FilenameUtils.getExtension(file.getOriginalFilename()));
        file.transferTo(f);
        return f;
    }

   /**
     * 处理请求数据
     * @param file
     * @param fileType 
     * @param accessToken
     * @return
     */
    public String uploadFile(File file, String fileType,String accessToken){
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type="+fileType;
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("multipart/form-data");
        headers.setContentType(type);
        headers.setContentLength(file.length());
        headers.setContentDispositionFormData("media",file.getName());
        MultiValueMap param = new LinkedMultiValueMap<>();
        FileSystemResource resource = new FileSystemResource(file.getPath());
        param.add("file",resource);
        HttpEntity> formEntity = new HttpEntity<>(param, headers);
        ResponseEntity data = restTemplate.postForEntity(url,formEntity,String.class);
        String body = data.getBody();
        return body;
    }

4.HttpClient类

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author fcx
 * @create 2022-04-15 10:37
 **/
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("An instance of HttpsURLConnection is expected");
            }

            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

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

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));

            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });

            super.prepareConnection(httpsConnection, httpMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * We need to invoke sslSocket.setEnabledProtocols(new String[] {"SSLv3"});
     * see http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html (Java 8 section)
     */
    // SSLSocketFactory用于创建 SSLSockets
    private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

        private final SSLSocketFactory delegate;

        public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }

        // 返回默认启用的密码套件。除非一个列表启用,对SSL连接的握手会使用这些密码套件。
        // 这些默认的服务的最低质量要求保密保护和服务器身份验证
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }

        // 返回的密码套件可用于SSL连接启用的名字
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }


        @Override
        public Socket createSocket(final Socket socket, final String host, final int port,
                                   final boolean autoClose) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
            return overrideProtocol(underlyingSocket);
        }


        @Override
        public Socket createSocket(final String host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final InetAddress host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }

        private Socket overrideProtocol(final Socket socket) {
            if (!(socket instanceof SSLSocket)) {
                throw new RuntimeException("An instance of SSLSocket is expected");
            }
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
            return socket;
        }
    }


}

如果在调用的时候出现了javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)异常 需要配置JM的参数设置,经过百度查询

原因: 配置文件中禁用 TLSv1, TLSv1.1

修改如下:

 把..\Java\jdk-11.0.11\conf\security文件下的java.security文件

将 :

jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \
     DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
     include jdk.disabled.namedCurves

替换为:

jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
     DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
     include jdk.disabled.namedCurves

测试post:

企业微信上传临时素材文件_第1张图片

 

你可能感兴趣的:(数据库,后端,微信开放平台)