https的post和get认证忽略

	
        org.apache.httpcomponents
        httpclient
        4.5.2
    
    
        org.apache.httpcomponents
        httpmime
        4.5.3
    
    
        org.apache.httpcomponents
        httpcore
        4.4.5
    



 import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

	import java.net.HttpURLConnection;
import java.net.URL;

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


private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager,X509TrustManager {
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public boolean isServerTrusted(X509Certificate[] certs) {
        return true;
    }
    public boolean isClientTrusted(X509Certificate[] certs) {
        return true;
    }
    public void checkServerTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }
    public void checkClientTrusted(X509Certificate[] certs, String authType)
            throws CertificateException {
        return;
    }
}

/**
* @desc :微信上传素材的请求方法 调用
* @param requestUrl 微信上传临时素材的接口url
* @param file 要上传的文件
* @return String 上传成功后,微信服务器返回的消息
*/

public static String httpRequest(String requestUrl, File file) {
    StringBuffer buffer = new StringBuffer();
    try{
        //1.建立连接
        URL url = new URL(requestUrl);

        if("https".equalsIgnoreCase(url.getProtocol())){
            ignoreSsl();
        }
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接

        //1.1输入输出设置
        httpUrlConn.setDoInput(true);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setUseCaches(false); // post方式不能使用缓存
        //1.2设置请求头信息
        httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
        httpUrlConn.setRequestProperty("Charset", "UTF-8");
        //1.3设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        httpUrlConn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ BOUNDARY);

        // 请求正文信息
        // 第一部分:
        //2.将文件头输出到微信服务器
        StringBuilder sb = new StringBuilder();
        // 必须多两道线
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length()
                + "\";filename=\""+ file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");
        byte[] head = sb.toString().getBytes("utf-8");
        // 获得输出流
        OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
        // 将表头写入输出流中:输出表头
        outputStream.write(head);

        //3.将文件正文部分输出到微信服务器
        // 把文件以流文件的方式 写入到微信服务器中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        //图片大于2M会出问题,企业微信不准有大于2M的,这里先设置1M,后期有问题改大
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            outputStream.write(bufferOut, 0, bytes);
        }
        in.close();
        //4.将结尾部分输出到微信服务器
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
        outputStream.write(foot);
        outputStream.flush();
        outputStream.close();


        //5.将微信服务器返回的输入流转换成字符串
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        bufferedReader.close();
        inputStreamReader.close();
        // 释放资源
        inputStream.close();
        inputStream = null;
        httpUrlConn.disconnect();


    } catch (Exception e) {
        System.out.println("发送POST请求出现异常!" + e);
        e.printStackTrace();
    }
    return buffer.toString();
}

-----------------上面是post 下面是get

private static CloseableHttpClient createHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(null, (chain, authType) -> true)
            .build();

    SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
            new NoopHostnameVerifier());

    return HttpClients.custom().setSSLSocketFactory(sslSf).build();
}

 protected String toAuth(String Get_Token_Url) throws IOException {
    String resp ="";
    try (CloseableHttpClient httpClient = createHttpClient()) {
        HttpGet httpGet = new HttpGet(Get_Token_Url);
//            String resp;
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
            HttpEntity entity = httpResponse.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);

//                System.out.printf(result);
            return  resp;
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();

    }
//        httpClient = HttpClients.createDefault();
//        httpGet = new HttpGet(Get_Token_Url);
//        CloseableHttpResponse response = 	httpClient.execute(httpGet);
//        System.out.println(response.toString());
//        String resp;
//        try {
//            HttpEntity entity = response.getEntity();
//            System.out.println(response.getAllHeaders());
//            resp = EntityUtils.toString(entity, "utf-8");
//            EntityUtils.consume(entity);
//        } finally {
//            response.close();
//        }
//
    return resp;
}

你可能感兴趣的:(java)