问题
I tried 2 hours and could not make it work. This is what I did:
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
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}"
}
}
回答2:
Proxy authentication uses different HTTP header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization), so simply adding the header should work for you.
String basicAuthCredentials = Base64.getEncoder().encodeToString(String.format("%s:%s", username,password).getBytes());
http.setHeaders(['Proxy-Authorization' : "Basic " + basicAuthCredentials])
来源:https://stackoverflow.com/questions/18010892/how-to-use-httpbuilder-behind-a-proxy-with-authentication