How to use HTTPBuilder behind a proxy with authent

2019-07-18 13:22发布

问题:

I tried 2 hours and could not make it work. This is what I did:

  1. grails add-proxy myproxy "--host=<host>" "--port=<port>" "--username=<username>" "--password=<psw>"
    grails use-proxy myproxy
    

    I got connection refused error which mean the proxy is not working

  2. In my groovy file, I add the proxy

    def http = new HTTPBuilder("http://http://headers.jsontest.com/")
    http.setProxy(host, port, "http");
    http.request(Method.GET, JSON) {
        uri.path = '/'
        response.success = { resp, json ->
                        .....
        }
    }
    

    I then get groovyx.net.http.HttpResponseException: Proxy Authentication Required

I could not figure out how I set the user/psw for the proxy to make it work

I tried the java way, not working

    System.setProperty("http.proxyUser", username);
    System.setProperty("http.proxyPassword", password);

and

    Authenticator.setDefault(new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, .toCharArray());
    }});

Does anyone know how to do this?

回答1:

Don't know if it will work, but there's some code over here that shows you should do:

import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import org.apache.http.auth.*

def http = new HTTPBuilder( 'http://www.ipchicken.com'  )

http.client.getCredentialsProvider().setCredentials(
    new AuthScope("myproxy.com", 8080),
    new UsernamePasswordCredentials("proxy-username", "proxy-password")
)

http.setProxy('myproxy.com', 8080, 'http')

http.request( GET, TEXT ){ req ->
    response.success = { resp, reader ->
        println "Response: ${reader.text}"
    }
}