How do a send an HTTPS request through a proxy in Java?

前端 未结 2 1803
暗喜
暗喜 2020-11-30 21:11

I am trying to send a request to a server using the HttpsUrlConnection class. The server has certificate issues, so I set up a TrustManager that trusts everything, as well

2条回答
  •  一生所求
    2020-11-30 21:35

    Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

    From their sample code:

      HttpClient httpclient = new HttpClient();
      httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
    
      /* Optional if authentication is required.
      httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
       new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
      */
    
      PostMethod post = new PostMethod("https://someurl");
      NameValuePair[] data = {
         new NameValuePair("user", "joe"),
         new NameValuePair("password", "bloggs")
      };
      post.setRequestBody(data);
      // execute method and handle any error responses.
      // ...
      InputStream in = post.getResponseBodyAsStream();
      // handle response.
    
    
      /* Example for a GET reqeust
      GetMethod httpget = new GetMethod("https://someurl");
      try { 
        httpclient.executeMethod(httpget);
        System.out.println(httpget.getStatusLine());
      } finally {
        httpget.releaseConnection();
      }
      */
    

提交回复
热议问题