Java and HTTPS url connection without downloading certificate

前端 未结 6 466
自闭症患者
自闭症患者 2020-11-27 12:32

This code connects to a HTTPS site and I am assuming I am not verifying the certificate. But why don\'t I have to install a certificate locally for the site? Shouldn\'t I

6条回答
  •  盖世英雄少女心
    2020-11-27 12:46

    A simple, but not pure java solution, is to shell out to curl from java, which gives you complete control over how the request is done. If you're just doing this for something simple, this allows you to ignore certificate errors at times, by using this method. This example shows how to make a request against a secure server with a valid or invalid certificate, pass in a cookie, and get the output using curl from java.

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class MyTestClass
    {
      public static void main(String[] args) 
      {
        String url = "https://www.google.com";
        String sessionId = "faf419e0-45a5-47b3-96d1-8c62b2a3b558";
    
        // Curl options are:
        // -k: ignore certificate errors
        // -L: follow redirects
        // -s: non verbose
        // -H: add a http header
    
        String[] command = { "curl", "-k", "-L", "-s", "-H", "Cookie: MYSESSIONCOOKIENAME=" + sessionId + ";", "-H", "Accept:*/*", url };
        String output = executeShellCmd(command, "/tmp", true, true);
        System.out.println(output);
      }
    
      public String executeShellCmd(String[] command, String workingFolder, boolean wantsOutput, boolean wantsErrors)
      {
        try
        {
          ProcessBuilder pb = new ProcessBuilder(command);
          File wf = new File(workingFolder);
          pb.directory(wf);
    
          Process proc = pb.start();
          BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
          BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
    
          StringBuffer sb = new StringBuffer();
          String newLine = System.getProperty("line.separator");
          String s;
    
          // read stdout from the command
          if (wantsOutput)
          {
            while ((s = stdInput.readLine()) != null)
            {
              sb.append(s);
              sb.append(newLine);
            }
          }
    
          // read any errors from the attempted command
          if (wantsErrors)
          {
            while ((s = stdError.readLine()) != null)
            {
              sb.append(s);
              sb.append(newLine);
            }
          }
    
          String result = sb.toString();
    
          return result;
        }
        catch (IOException e)
        {
          throw new RuntimeException("Problem occurred:", e);
        }
      }
    
    
    }
    

提交回复
热议问题