soft

soft

java 访问HTTP(S)

public static String okHttpPost(String url,String paramJsonString){
    try{
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json; charset=UTF-8");
        RequestBody body = RequestBody.create(mediaType, paramJsonString);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Accept", "application/json")
                .addHeader("Content-type", "application/json")
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

public static String erkHttp(String uri,String password,String queryData){
    try{
        //URL url = new URL("http://121.62.60.60:9200/sample/_search?filter_path=**.hits._source.message");
        URL url = new URL(uri);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("GET");
        httpConn.setRequestProperty("Content-Type", "application/json");
        //byte[] message = ("elastic:8881130py").getBytes("UTF-8");
        byte[] message = ("elastic:"+password).getBytes("UTF-8");
        String basicAuth = DatatypeConverter.printBase64Binary(message);
        httpConn.setRequestProperty("Authorization", "Basic " + basicAuth);
        httpConn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
        //writer.write("{  \"query\": {    \"match\": {\"decode_data.domain\": \"test.com\"}  }}");
        writer.write(queryData);
        writer.flush();
        writer.close();
        httpConn.getOutputStream().close();
        InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                ? httpConn.getInputStream()
                : httpConn.getErrorStream();
        Scanner s = new Scanner(responseStream).useDelimiter("\\A");
        String response = s.hasNext() ? s.next() : "";
        return  response;
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}


public static  String erkHttpS(String uri,String password,String queryData){
    // Load Certificate
    // curl --cacert /etc/elasticsearch/certstp_ca.crt -u elastic:Omg3GxT=MGMkkWLa-+sd https://localhost:9200/sample/_search -d'{  "query": {    "match": {"decode_data.domain": "test.com"}  }}'
    String result="";
    try {
        //请求超时时间,这个时间定义了socket读数据的超时时间,也就是连接到服务器之后到从服务器获取响应数据需要等待的时间,发生超时,会抛出SocketTimeoutException异常。
         final int SOCKET_TIME_OUT = 60000;
        //连接超时时间,这个时间定义了通过网络与服务器建立连接的超时时间,也就是取得了连接池中的某个连接之后到接通目标url的连接等待时间。发生超时,会抛出ConnectionTimeoutException异常
         final int CONNECT_TIME_OUT = 60000;

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        // 这里的路径为证书存放路径
        final String crtPath="/etc/elasticsearch/certs/http_ca.crt";
        Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(crtPath));

        // Create TrustStore
        KeyStore trustStoreContainingTheCertificate = KeyStore.getInstance("JKS");
        trustStoreContainingTheCertificate.load(null, null);

        // AddCertificate  第一个参数为证书别名, 可以任取
        trustStoreContainingTheCertificate.setCertificateEntry("XYZ", certificate);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStoreContainingTheCertificate);

        // Create SSLContext   我这里协议为TLSv1.2
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null,trustManagerFactory.getTrustManagers(),null);
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);

        // Create custom httpClient    创建自定义httpClient连接
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        try{
            // POST请求
            //HttpPost method = new HttpPost("https://www.apapanet.com/");
            //get
            HttpPost postRequest = new HttpPost(uri);
            //System.out.println("executing request" + method.getRequestLine());
            postRequest.setHeader("Content-type", "application/json;charset=utf-8");
            postRequest.setHeader("Accept", "application/json");
            byte[] message = ("elastic:"+password).getBytes("UTF-8");
            String basicAuth = DatatypeConverter.printBase64Binary(message);
            postRequest.setHeader("Authorization","Basic " + basicAuth);

           //setConfig,添加配置,如设置请求超时时间,连接超时时间
            org.apache.http.client.config.RequestConfig reqConfig = org.apache.http.client.config.RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT).setConnectTimeout(CONNECT_TIME_OUT).build();
            postRequest.setConfig(reqConfig);

            //setEntity,添加内容
            HttpEntity entity = new StringEntity(queryData);
            postRequest.setEntity(entity);

            CloseableHttpResponse response = null;
            response = httpClient.execute(postRequest);

            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                String body = EntityUtils.toString(response.getEntity());
                if(StringUtils.isNotBlank(body)){
                    //System.out.println("body: "+body);
                    result= body;
                }
            }
            response.close();
        }
        finally {
            httpClient.close();
        }
    } catch (Exception e ){
        e.printStackTrace();
    }
    return result;
}


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

联系我 331434376    15629529961