How to use HTTPBuilder behind a proxy with authentication

蓝咒 提交于 2019-12-11 01:34:55

问题


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}"
    }
}



回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!