码迷,mamicode.com
首页 > Web开发 > 详细

httpUtils

时间:2018-07-13 20:46:23      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:getname   tar   response   sock   sls   session   mitm   set   img   

httpUtils

技术分享图片
package com.icil.edi.ws.printService.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class URLHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(URLHttpUtils.class);

    /*
     * public static void httpsSkipCertificates() {
     * 
     * try { trustAllHttpsCertificates(); } catch (Exception e) { // TODO
     * Auto-generated catch block e.printStackTrace(); }
     * 
     * }
     */

    public synchronized static String HttpClientRequest(String message, Header header, String operation, String url) {

        RequestEntity entity = null;
        String response = null;
        PostMethod postMethod = null;
        try {
            logger.info("Enter into HttpClientRequest method ");
            entity = new ByteArrayRequestEntity(message.getBytes("UTF-8"));
            HttpClient httpClient = new HttpClient();
            postMethod = new PostMethod(url + operation);
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            if (header != null) {
                postMethod.setRequestHeader(header);
            }
            postMethod.setRequestEntity(entity);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        logger.info("Complete of the HttpClientRequest method");
        return response;
    }

    public synchronized static String HttpClientRequest(String jsonMessage, String targetUrl, Header header) {

        logger.info("debug the json message " + jsonMessage);
        logger.info("debug targetUrl " + targetUrl);
        // logger.info("debug the "+header.getName()+" ----- "+header.getValue());

        RequestEntity entity = null;
        String response = null;
        PostMethod postMethod = null;
        try {
            logger.info("Enter into HttpClientRequest method ");
            entity = new ByteArrayRequestEntity(jsonMessage.getBytes("UTF-8"));
            HttpClient httpClient = new HttpClient();
            postMethod = new PostMethod(targetUrl);
            postMethod.addRequestHeader("Content-Type", "application/json");
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            if (header != null) {
                postMethod.setRequestHeader(header);
            }
            postMethod.setRequestEntity(entity);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        logger.info("Complete of the HttpClientRequest method");
        return response;

        /*
         * Client client = ClientBuilder.newClient(); Entity payload =
         * Entity.json(jsonMessage); Response response = client.target(targetUrl).
         * request(MediaType.APPLICATION_JSON_TYPE). header(header.getName(),
         * header.getValue()).post(payload); return response.getEntity().toString() ;
         */
    }

    /**
     * @param url , postData @return String @throws
     */
    public synchronized static String postURLRequest(String url, String postData) {

        logger.debug("Enter into postURLRequest method .");
        StringBuffer buffer = new StringBuffer();
        try {
            // here skip the https certificate verify, or should install cert into JDK
            // .currently skip the
            // validate for certificate.
            // URLHttpUtils.httpsSkipCertificates();
            trustAllHttpsCertificates();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            URL obj = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
            conn.setRequestMethod("POST");
            // USPS web service require to set this content-type.
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // open the key that can send the data to webservice.
            conn.setDoOutput(true);
            // open the key that can receive the data from webservice.
            conn.setDoInput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(postData);
            wr.flush();
            wr.close();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.debug("The response content : " + buffer.toString());
        logger.debug("Complete in postURLRequest method .");
        return buffer.toString();
    }

    /**
     * @param url , postData @return String @throws
     */
    public synchronized static String deleteURLRequest(String targetUrl, Map<String, String> map) {

        logger.info("Enter into getURLRequest method ");
        logger.info("debug targetUrl " + targetUrl);
        // logger.info("debug the "+header.getName()+" ----- "+header.getValue());

        RequestEntity entity = null;
        String response = null;
        DeleteMethod deleteMethod = null;
        try {

            HttpClient httpClient = new HttpClient();
            deleteMethod = new DeleteMethod(targetUrl);
            deleteMethod.addRequestHeader(map.get("apiKey"), map.get("apiValue"));
            httpClient.executeMethod(deleteMethod);
            response = deleteMethod.getResponseBodyAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            deleteMethod.releaseConnection();
        }
        logger.info("Complete of the getURLRequest method");
        return response;

    }

    /**
     * @param url , postData @return String @throws
     */
    public synchronized static String getURLRequest(String targetUrl, Map<String, String> map) {

        logger.info("Enter into getURLRequest method ");
        logger.info("debug targetUrl " + targetUrl);
        // logger.info("debug the "+header.getName()+" ----- "+header.getValue());

        RequestEntity entity = null;
        String response = null;
        GetMethod getMethod = null;
        try {

            HttpClient httpClient = new HttpClient();
            getMethod = new GetMethod(targetUrl);
            getMethod.addRequestHeader(map.get("apiKey"), map.get("apiValue"));
            httpClient.executeMethod(getMethod);
            response = getMethod.getResponseBodyAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
        logger.info("Complete of the getURLRequest method");
        return response;

    }
    
    /**
     * @param url , postData @return String @throws
     */
    public synchronized static String postURLRequest2(String jsonMessage, String targetUrl, Map<String, String> map) {

        logger.info("Enter into postURLRequest2 method ");
        logger.info("debug the json message " + jsonMessage);
        logger.info("debug targetUrl " + targetUrl);
        // logger.info("debug the "+header.getName()+" ----- "+header.getValue());

        RequestEntity entity = null;
        String response = null;
        PostMethod postMethod = null;
        try {
            entity = new ByteArrayRequestEntity(jsonMessage.getBytes("UTF-8"));
            HttpClient httpClient = new HttpClient();
            postMethod = new PostMethod(targetUrl);
            postMethod.addRequestHeader("Content-Type", "application/json");
            postMethod.addRequestHeader(map.get("apiKey"), map.get("apiValue"));
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

            postMethod.setRequestEntity(entity);
            httpClient.executeMethod(postMethod);
            response = postMethod.getResponseBodyAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        logger.info("Complete of the HttpClientRequest method");
        return response;

    }
    
    
    // 2016-10-03, wrightdeng,#3257 add skip https verify function here.
    static HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            // TODO Auto-generated method stub
            return true;
        }
    };

    private synchronized static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }

    static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
}
View Code

 eg:

技术分享图片
//get 的使用


String response = URLHttpUtils.getURLRequest(url, null);



post ;的使用

String apiToken = PropertiesUtils.getConfigInfo(EdiServiceConstant.SECURITY_KEY, EdiServiceConstant.AIR21KEY);
        String userToken = PropertiesUtils.getConfigInfo(EdiServiceConstant.SECURITY_KEY, EdiServiceConstant.AIR21VALUE);
        // Assemble Authentication Header
        Header header = accountServiceFactory.getBasicAuthorizationHeader(apiToken, userToken);
////////////////////
    public Header getBasicAuthorizationHeader(String key,String value) {
            Header header = new Header();
            LOGGER.info("header key is :{}",key);
            header.setName(PrintConstant.Authorization);
            header.setValue("Basic "+Base64.getEncoder().encodeToString((key+":"+value).getBytes()));
        return header;
    }
//////////////////

 response = URLHttpUtils.HttpClientRequest(requestData, air21Url, header);
View Code

解析response:

import org.json.JSONObject;
import org.json.XML;

jsonObject = XML.toJSONObject(response);

httpUtils

标签:getname   tar   response   sock   sls   session   mitm   set   img   

原文地址:https://www.cnblogs.com/lshan/p/9307264.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!