Java implements httpGet Post Put Delete httpsPost request and returns the result

 /**
     * Send a GET method request to the specified URL
     *
     * @param url Send the request URL
     * @param param Request parameter, the request parameter should be in the form of name1=value1&name2=value2.
     * @return the response result of the remote resource represented by the URL
     */
    public static String sendGet (String url, String param) {
        
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // Open connection to URL
            URLConnection connection = realUrl.openConnection();
            // Set common request properties
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("timestamp ",timestamp);
            connection.setRequestProperty("CompanyCode",CompanyCode);
            connection.setRequestProperty("companyPassword",companyPassword);
            // establish the actual connection
            connection.connect();
            // get all response header fields
            Map<String, List<String>> map = connection.getHeaderFields();
            // Traverse all response header fields
            for (String key : map.keySet()) {
                logger.info(key + "--->" + map.get(key));
            }
            // Define BufferedReader input stream to read response from URL
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf -8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("An exception occurred when sending a GET request!" + e);
            e.printStackTrace();
        }
        // use a finally block to close the input stream
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Send a POST method request to the specified URL
     * @param url Send the requested URL
     * @param param Request parameters, the request parameters should be The form name1=value1&name2=value2.
     * The response result of the remote resource represented by @return
     */
    public static String sendPost (String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url) ;
            // Open the connection to the URL
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("timestamp",timestamp);
            conn.setRequestProperty("CompanyCode",CompanyCode);
            conn.setRequestProperty("companyPassword",companyPassword);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);            // Get the output stream corresponding to the URLConnection object
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());
            // send request parameters
            out.print(param);
            // flush output stream buffer
            out.flush();
            // define BufferedReader input stream to read URL response
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("An exception occurred when sending a POST request!"+e);
            e.printStackTrace();
        }
        //Use the finally block to close the output stream and input stream
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    / **
     * Send the request of the Put method to the specified URL
     * @param url The URL of the request
     * @param param request parameters,
     * @return represents the response result of the remote resource
     */
    public static String sendPut (String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection  conn = (HttpURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn.setRequestProperty("timestamp",timestamp);
            conn.setRequestProperty("CompanyCode",CompanyCode);
            conn.setRequestProperty("companyPassword",companyPassword);
            // The following two lines must be set to send a POST request
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // Get URLConnection The output stream corresponding to the object
            out = new PrintWriter(conn.getOutputStream());
            // send request parameters
            out.print(param);
            // flush the buffer of the output stream
            out.flush();
            // define the BufferedReader input stream to read Get the response of the URL
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("An exception occurred when sending a POST request!"+e);
            e.printStackTrace() ;
        }
        //Use finally block to close output stream, input stream
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch (IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
    /**
     * Send the request of the Put method to the specified URL
     * @param url The URL of the request
     * @param param The request parameter,
     * @return represents the response result of the remote resource
     */
    public static String sendDelete (String url, String param ) {
         String result = "";
         BufferedReader in = null;
         try {
             String urlNameString = url + "?" + param;
             URL realUrl = new URL(urlNameString);
             // Open connection to URL
             HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
             // set common request properties
             connection.setRequestProperty("accept", "*/*");
             connection.setRequestProperty("connection", "Keep-Alive");
             connection.setRequestProperty("user-agent",
                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
             connection.setRequestMethod("DELETE");
             connection.setRequestProperty("timestamp",timestamp);
             connection.setRequestProperty("CompanyCode",CompanyCode);
             connection.setRequestProperty("companyPassword",companyPassword);
             // 建立实际的连接
             connection.connect();
             // 获取所有响应头字段
             Map<String, List<String>> map = connection.getHeaderFields();
             // loop through all response header fields
             for (String key : map.keySet()) {
                 logger.info(key + "--->" + map.get(key));
             }
             // Define the BufferedReader input stream to read the URL's response
             in = new BufferedReader (new InputStreamReader(
                     connection.getInputStream(),"utf-8"));
             String line;
             while ((line = in.readLine()) != null) {
                 result += line;
             }
         } catch (Exception e) {
             logger.info("Error sending DELETE request!" + e);
             e.printStackTrace();
         }
         // Use finally block to close the input stream
         finally {
             try {
                 if (in != null) {
                     in.close();
                 }
             } catch (Exception e2) {
                 e2.printStackTrace();
             }
         }
         return result;

When you need to send a POST request of https, it will appear if you use the above POST

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target When you do not need to verify the certificate but you want to send an https request, the processing is as follows

In order to avoid it, we need to write another Post method for sending https requests. The method is as follows:

First customize a MyX509TrustManager to implement X509TrustManager

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;


public class MyX509TrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
        // TODO Auto-generated method stub
        
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }

}

然后在重新写POST方法 和上述HTTPpost相差只是多了红色字体部分 

/**
     * 发送httpsPost请求
     * */
    public static String sendPostHttps(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
            // 设置通用的请求属性
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = { new MyX509TrustManager() };
            // 初始化
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 获取SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "UTF-8");
            conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setSSLSocketFactory(ssf);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());
            out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
            return null;
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;

    }

就可以了




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325556592&siteId=291194637