zoukankan      html  css  js  c++  java
  • httpUtils

    httpUtils

    0.依赖:

        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
            <dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.1</version>
            </dependency>

     依赖:

        <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
            <dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.1</version>
            </dependency>

      最终整理:

    package com.icil.esolution.utils;
    
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.util.ArrayList;
    import java.util.Base64;
    import java.util.Map;
    
    import org.apache.commons.httpclient.Header;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.HttpStatus;
    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.methods.multipart.FilePart;
    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
    import org.apache.commons.httpclient.methods.multipart.Part;
    import org.apache.commons.httpclient.methods.multipart.StringPart;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.slf4j.MDC;
    import org.springframework.web.multipart.MultipartFile;
    
    /***********************************************************************
     * <PRE>
     *
     *  File Name       : URLHttpUtils.java
     * 
     *  Creation Date   : Aug 24, 2018
     * 
     *  Author          : sea
     * 
     * 
     * </PRE>
     ***************************************************************************/
    
    public class URLHttpUtils {
    
        private static final Logger logger = LoggerFactory.getLogger(URLHttpUtils.class);
    
        public static synchronized 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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                postMethod.releaseConnection();
            }
            logger.info("complete of the HttpClientRequest method");
            return response;
        }
    
        /**
         * 2018-08-26 sea add 3 try
         * 
         * @param jsonMessage
         * @param targetUrl
         * @param header
         * @return
         */
        public static synchronized String HttpClientPostRequest(String jsonMessage, String targetUrl, Header header) {
    
            logger.info("debug the json message " + jsonMessage);
            logger.info("debug targetUrl " + targetUrl);
    
            RequestEntity entity = null;
            String response = null;
            PostMethod postMethod = null;
            HttpClient httpClient = new HttpClient();
            try {
                logger.info("Enter into HttpClientRequest method ");
                entity = new ByteArrayRequestEntity(jsonMessage.getBytes("UTF-8"));
                postMethod = new PostMethod(targetUrl);
                postMethod.addRequestHeader("Content-Type", "application/json");
    //            postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                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 (Exception e) {
                logger.info("connect fail ,try to connect again!");
                e.printStackTrace();
                try {
                    httpClient.executeMethod(postMethod);
                    response = postMethod.getResponseBodyAsString();
                } catch (Exception e2) {
                    logger.info("connect second fail ,try to third  time  connect !");
                    e2.printStackTrace();
                    try {
                        httpClient.executeMethod(postMethod);
                        response = postMethod.getResponseBodyAsString();
                    } catch (Exception e3) {
                        logger.info("third  time  connect fail !");
                        e3.printStackTrace();
                        MDC.put("concectException", e3.toString());
                    }
                }
    
            } finally {
                postMethod.releaseConnection();
            }
            logger.info("Complete of the HttpClientRequest method");
            return response;
    
        }
    
        
        
        /**
         * @param url
         *        
         */
        public static synchronized String deleteURLRequest(String targetUrl, Map<String, String> map) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl " + targetUrl);
    
            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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                deleteMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
    
        }
    
        /**
         * @param url
         *            , postData @return String @throws
         */
        public static synchronized String getURLRequest(String targetUrl, Map<String, String> map) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl " + targetUrl);
    
            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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                getMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
    
        }
    
        /**
         * sea add 2 try again 2018-08-24
         * 
         * @param targetUrl
         * @param header
         * @return
         */
        public static synchronized String getURLRequest(String targetUrl, Header header) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl is {}", targetUrl);
    
            String response = null;
            GetMethod getMethod = null;
            HttpClient httpClient = new HttpClient();
            getMethod = new GetMethod(targetUrl);
            if (header != null) {
                getMethod.addRequestHeader(header);
            }
            try {
                httpClient.executeMethod(getMethod);
                response = getMethod.getResponseBodyAsString();
            } catch (Exception e) {
                logger.info("get connect fail, try to second connect");
                e.printStackTrace();
                try {
                    httpClient.executeMethod(getMethod);
                    response = getMethod.getResponseBodyAsString();
                } catch (Exception e1) {
                    logger.info("get connect fail, try to third time connect");
                    e1.printStackTrace();
                    try {
                        httpClient.executeMethod(getMethod);
                        response = getMethod.getResponseBodyAsString();
                    } catch (Exception e2) {
                        logger.info("It have third time connect but still connect fail,and exception is {}", e2);
                        MDC.put("concectException", e2.toString());
                        e2.printStackTrace();
                    }
                }
            } finally {
                getMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
        }
        
        
        
        /**
         * @Desc POST方式 传带文件的调用
         * @return
         * @throws Exception
         */
        public static String postFileMethod(String url,Map<String,String> params,String multipartFileName,MultipartFile multipartFile,Header header){
            
                  HttpClient client = new HttpClient();
                   PostMethod method = new PostMethod(url);
                   method.addRequestHeader(header);
                   String response= null;
                   int result=0;
                try {
                    File file = null;
                    if(multipartFile!=null)
                    {
                         //transfer  MultipartFile to file
                        String filename = multipartFile.getName();
                        String originalFilename = multipartFile.getOriginalFilename();
                        int lastIndexOf = originalFilename.lastIndexOf(".");
                        String suffix = originalFilename.substring(lastIndexOf);
                        file=File.createTempFile(filename, suffix);
                        multipartFile.transferTo(file);
                        file.deleteOnExit();  
                        
                        FilePart filePart = new FilePart(multipartFileName,file);//文件参数
                        
                        //set params
                        ArrayList<StringPart> paramList = new ArrayList<>();
                        if(params.size()>0){
                            
                            for (Map.Entry<String, String> entry : params.entrySet())
                            {  
                                StringPart param = new StringPart(entry.getKey(), entry.getValue());  //普通参数
                                paramList.add(param);
                            }
                        }
                        int size = paramList.size();
                         Part[] parts =new Part[size+1];  
                       
                         for(int i=0;i<size;i++){
                             parts[i]=paramList.get(i);
                         }
                         parts[size]=filePart;
                    
                        MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams());    //封装了普通字段和文件字段
                        method.setRequestEntity(mre );
                         result = client.executeMethod(method);
                         response = method.getResponseBodyAsString();
                          // response=  responseHandler(result,method);  //NOSONAR
                    }
                    } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("post data to 3th fail ,try to post again.");
                     try {
                            result = client.executeMethod(method);
    //                           response=  responseHandler(result,method); //NOSONAR
                               response = method.getResponseBodyAsString();
                    } catch (Exception e2) {
                        logger.info("post data to 3th second tine fail ,try to post again.");
                        try {
                              result = client.executeMethod(method);
    //                           response=  responseHandler(result,method); //NOSONAR
                               response = method.getResponseBodyAsString();
                        } catch (Exception e3) {
                            e3.printStackTrace();
                            MDC.put("concectException", e3.toString());
                            logger.info("post data to 3th third  tine fail .");
                        }
                    }
                }
                  finally {
                    method.releaseConnection();
                }
                logger.info("end the PostMethodFile method");
                return  response;
        }
        
        
        /**
         * test post method
         * @param result
         * @param method
         * @return
         * @throws IOException
         */
        /**
         * @Desc POST方式 传带文件的调用
         * @return
         * @throws Exception
         */
        public static String postFile(String url,String multipartFileName,MultipartFile multipartFile,Header header){
            
                  HttpClient client = new HttpClient();
                   PostMethod method = new PostMethod(url);
                   method.addRequestHeader(header);
                   String response= null;
                   int result=0;
                try {
                    File file = null;
                    if(multipartFile!=null)
                    {
                         //transfer  MultipartFile to file
                        String filename = multipartFile.getName();
                        String originalFilename = multipartFile.getOriginalFilename();
                        int lastIndexOf = originalFilename.lastIndexOf(".");
                        String suffix = originalFilename.substring(lastIndexOf);
                        file=File.createTempFile(filename, suffix);
                        multipartFile.transferTo(file);
                        file.deleteOnExit();  
                        FilePart filePart = new FilePart(multipartFileName,file);//文件参数
                        Part[] parts ={filePart};
                    
                        MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams());    //封装了普通字段和文件字段
                        method.setRequestEntity(mre);
                    }    
                         result = client.executeMethod(method);
                         response = method.getResponseBodyAsString();
                          
                           response=  responseHandler(result,method);  //NOSONAR
                    
                    } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("post data to 3th fail ,try to post again.");
                     try {
                            result = client.executeMethod(method);
                           response=  responseHandler(result,method); //NOSONAR
                             //  response = method.getResponseBodyAsString();
                    } catch (Exception e2) {
                        logger.info("post data to 3th second tine fail ,try to post again.");
                        try {
                              result = client.executeMethod(method);
                               response=  responseHandler(result,method); //NOSONAR
                             //  response = method.getResponseBodyAsString();
                        } catch (Exception e3) {
                            e3.printStackTrace();
                            MDC.put("concectException", e3.toString());
                            logger.info("post data to 3th third  tine fail .");
                        }
                    }
                }
                  finally {
                    method.releaseConnection();
                }
                logger.info("end the PostMethodFile method");
                return  response;
        }
        
         private static String responseHandler(int result, PostMethod method) throws IOException {
            if (result == HttpStatus.SC_OK) {
                InputStream in = method.getResponseBodyAsStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                return URLDecoder.decode(baos.toString(), "UTF-8");
            } else {
                return null;
            }
        }
    
        /**
         * transfer InputStream to a File
         * @param ins
         * @param file
         */
        public static void inputStreamToFile(InputStream ins,File file) {
              try {
               OutputStream os = new FileOutputStream(file);
               int bytesRead = 0;
               byte[] buffer = new byte[8192];
               while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
               }
               os.close();
               ins.close();
              } catch (Exception e) {
               e.printStackTrace();
              }
             }
        
    
        /**
         * 2018-08-24 Sea add
         * @param key
         * @param value
         * @return
         */
        public static Header getBasicAuthorizationHeader(String key, String value) {
            Header header = new Header();
            logger.info("header key is :{} ", key);
            header.setName("Authorization");
            header.setValue("Basic " + Base64.getEncoder().encodeToString((key + ":" + value).getBytes()));
            return header;
        }
    
        
        
    }
    View Code

    post 带文件上传 

    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); 
    method.addRequestHeader(header);
    method.addRequestHeader(new Header("Accept","application/json"));
    // 视具体情况而定,可以从浏览器或postman查看下请求的header
    method.addRequestHeader("accept", "application/xml"); 
    //这里设置具体编码,视具体接口而定 ,这里可以解决response 乱码问题
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        /**
         * @Desc POST方式 传带文件的调用
         * @return
         * @throws Exception
         */
        public static String postFileMethod(String url,Map<String,String> params,String multipartFileName,MultipartFile multipartFile,Header header){
            
                  HttpClient client = new HttpClient();
                   PostMethod method = new PostMethod(url);
                   method.addRequestHeader(header);
                   String response= null;
                   int result=0;
                try {
                    File file = null;
                    FilePart filePart =null;
                    if(multipartFile!=null)
                    {
                         //transfer  MultipartFile to file
                        String filename = multipartFile.getName();
                        String originalFilename = multipartFile.getOriginalFilename();
                        int lastIndexOf = originalFilename.lastIndexOf(".");
                        String suffix = originalFilename.substring(lastIndexOf);
                        file=File.createTempFile(filename, suffix);
                        multipartFile.transferTo(file);
                        file.deleteOnExit();  
                        
                         filePart = new FilePart(multipartFileName,file);//文件参数
                        
                    }
                        //set params
                        ArrayList<StringPart> paramList = new ArrayList<>();
                        if(params.size()>0){
                            
                            for (Map.Entry<String, String> entry : params.entrySet())
                            {  
                                StringPart param = new StringPart(entry.getKey(), entry.getValue());  //普通参数
                                paramList.add(param);
                            }
                        }
                        int size = paramList.size();
                        Part[] parts =null;
                        //if  filePart is not null
                        if(filePart!=null){
                             parts =new Part[size+1];  
                            for(int i=0;i<size;i++){
                                parts[i]=paramList.get(i);
                            }
                            parts[size]=filePart;
                        }else {
                             parts =new Part[size];  
                            for(int i=0;i<size;i++){
                                parts[i]=paramList.get(i);
                            }
                        }
                    
                        MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams());    //封装了普通字段和文件字段
                        method.setRequestEntity(mre );
                         result = client.executeMethod(method);
                         response = method.getResponseBodyAsString();
                          // response=  responseHandler(result,method);  //NOSONAR
                    
                    } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("post data to 3th fail ,try to post again.");
                     try {
                            result = client.executeMethod(method);
    //                           response=  responseHandler(result,method); //NOSONAR
                               response = method.getResponseBodyAsString();
                    } catch (Exception e2) {
                        logger.info("post data to 3th second tine fail ,try to post again.");
                        try {
                              result = client.executeMethod(method);
    //                           response=  responseHandler(result,method); //NOSONAR
                               response = method.getResponseBodyAsString();
                        } catch (Exception e3) {
                            e3.printStackTrace();
                            MDC.put("concectException", e3.toString());
                            logger.info("post data to 3th third  tine fail .");
                        }
                    }
                }
                  finally {
                    method.releaseConnection();
                }
                logger.info("end the PostMethodFile method");
                return  response;
        }
    View Code

    1.

    package com.icil.esolution.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.Base64;
    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;
    import org.slf4j.MDC;
    
    
    
    public class URLHttpUtils {
    
        private static final Logger logger = LoggerFactory.getLogger(URLHttpUtils.class);
    
        public static synchronized 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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                postMethod.releaseConnection();
            }
            logger.info("complete of the HttpClientRequest method");
            return response;
        }
    
        /**
         * 2018-08-26 sea add 3 try
         * @param jsonMessage
         * @param targetUrl
         * @param header
         * @return
         */
        public static synchronized String HttpClientPostRequest(String jsonMessage, String targetUrl, Header header) {
    
            logger.info("debug the json message " + jsonMessage);
            logger.info("debug targetUrl " + targetUrl);
    
            RequestEntity entity = null;
            String response = null;
            PostMethod postMethod = null;
            HttpClient httpClient = new HttpClient();
            try {
                logger.info("Enter into HttpClientRequest method ");
                entity = new ByteArrayRequestEntity(jsonMessage.getBytes("UTF-8"));
                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 (Exception e) {
                logger.info("connect fail ,try to connect again!");
                e.printStackTrace();
                try {
                    httpClient.executeMethod(postMethod);
                    response = postMethod.getResponseBodyAsString();
                } catch (Exception e2) {
                    logger.info("connect second fail ,try to third  time  connect !");
                    e2.printStackTrace();
                    try {
                        httpClient.executeMethod(postMethod);
                        response = postMethod.getResponseBodyAsString();
                    } catch (Exception e3) {
                        logger.info("third  time  connect fail !");
                        e3.printStackTrace();
                        MDC.put("concectException", e3.toString());
                    }
                }
    
            } finally {
                postMethod.releaseConnection();
            }
            logger.info("Complete of the HttpClientRequest method");
            return response;
    
        }
    
        /**
         * @param url , postData @return String @throws
         */
        public static synchronized 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 is : {}", buffer.toString());
            logger.debug("Complete in postURLRequest method .");
            return buffer.toString();
        }
    
        /**
         * @param url , postData @return String @throws
         */
        public static synchronized String deleteURLRequest(String targetUrl, Map<String, String> map) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl " + targetUrl);
    
            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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                deleteMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
    
        }
    
        /**
         * @param url , postData @return String @throws
         */
        public static synchronized String getURLRequest(String targetUrl, Map<String, String> map) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl " + targetUrl);
    
            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) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                getMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
    
        }
    
        /**
         * sea add 2 try again 2018-08-24
         * 
         * @param targetUrl
         * @param header
         * @return
         */
        public static synchronized String getURLRequest(String targetUrl, Header header) {
    
            logger.info("Enter into getURLRequest method ");
            logger.info("debug targetUrl is {}", targetUrl);
    
            String response = null;
            GetMethod getMethod = null;
            HttpClient httpClient = new HttpClient();
            getMethod = new GetMethod(targetUrl);
            if (header != null) {
                getMethod.addRequestHeader(header);
            }
            try {
                httpClient.executeMethod(getMethod);
                response = getMethod.getResponseBodyAsString();
            } catch (Exception e) {
                logger.info("get connect fail, try to second connect");
                e.printStackTrace();
                try {
                    httpClient.executeMethod(getMethod);
                    response = getMethod.getResponseBodyAsString();
                } catch (Exception e1) {
                    logger.info("get connect fail, try to third time connect");
                    e1.printStackTrace();
                    try {
                        httpClient.executeMethod(getMethod);
                        response = getMethod.getResponseBodyAsString();
                    } catch (Exception e2) {
                        logger.info("It have third time connect but still connect fail,and exception is {}", e2);
                        MDC.put("concectException", e2.toString());
                        e2.printStackTrace();
                    }
                }
            } finally {
                getMethod.releaseConnection();
            }
            logger.info("Complete of the getURLRequest method");
            return response;
    
        }
    
        /**
         * @param url , postData @return String @throws
         */
        public static synchronized 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);
    
            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) {
                e.printStackTrace();
            } catch (IOException e) {
                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());
                return true;
            }
        };
    
        private static synchronized 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;
            }
        }
    
        /**
         * 2018-08-24 Sea add
         * 
         * @param key
         * @param value
         * @return
         */
        public static Header getBasicAuthorizationHeader(String key, String value) {
            Header header = new Header();
            logger.info("header key is :{} ", key);
            header.setName("Authorization");
            header.setValue("Basic " + Base64.getEncoder().encodeToString((key + ":" + value).getBytes()));
            return header;
        }
    
    }
    View Code

    2.不推荐2

    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

    post  带文件上传

    一、PostMethod一般请求
        /**
         * POST方式
         * @return
         * @throws Exception
         */
        public static String PostMethodTest() throws Exception{
            System.out.println("开始");
    
                HttpClient client = new HttpClient();
                PostMethod method = new PostMethod(URI);
                try{
    
                    method.addRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") );    
    
        //          method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    
                    method.addParameter(new NameValuePair("appid", "XXXX") );
                    method.addParameter(new NameValuePair("appkey", "XXXX") );
    
        //          method.addParameter("appid", "XXXX");
        //          method.addParameter("appkey", "XXXX");
    
                    int result = client.executeMethod(method);
                    if (result == HttpStatus.SC_OK) {
                        InputStream in = method.getResponseBodyAsStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        return URLDecoder.decode(baos.toString(), "UTF-8");
                    } else {
                        throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
                    }
                }finally {
                    method.releaseConnection();
                }
    
        }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    二、PostMethod带文件方式
        /**
         * POST方式 传带文件的调用
         * @return
         * @throws Exception
         */
        public static String PostMethodFileTest() throws Exception{
            System.out.println("开始");
    
                HttpClient client = new HttpClient();
                PostMethod method = new PostMethod(URI);
                try{
    
                    FilePart filePart = new FilePart("file",new File("D:\8\5972-41-2017-06-07-1440-16406.wav"));//文件参数
                    StringPart questionId = new StringPart("questionId","10001");//普通参数
                    StringPart userId = new StringPart("userId","765709");//普通参数
                    StringPart homeworkId = new StringPart("homeworkId","950");//普通参数
    
                    Part[] parts ={filePart,questionId,userId,homeworkId};
                    MultipartRequestEntity mre=new MultipartRequestEntity(parts ,method.getParams());    //封装了普通字段和文件字段
                    method.setRequestEntity(mre );
                    int result = client.executeMethod(method);
                    if (result == HttpStatus.SC_OK) {
                        InputStream in = method.getResponseBodyAsStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        return URLDecoder.decode(baos.toString(), "UTF-8");
                    } else {
                        throw new Exception("HTTP ERROR Status: " + method.getStatusCode() + ":" + method.getStatusText());
                    }
                }finally {
                    method.releaseConnection();
                }
        }
    View Code

    解析response:

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

    jsonObject = XML.toJSONObject(response);

  • 相关阅读:
    ISC2016训练赛 phrackCTF--Classical CrackMe
    JCTF 2014 小菜一碟
    攻防世界--ReverseMe-120
    lstm torch
    pandas 处理 纽约签到数据集
    python datatime
    tf.keras 模型 多个输入 tf.data.Dataset
    python **kwarg和*args
    java 优先队列 大根堆
    python总结
  • 原文地址:https://www.cnblogs.com/lshan/p/9307264.html
Copyright © 2011-2022 走看看