java - Spring RestTemplate and Proxy Auth -
i'm trying rest calls spring. understand, right way go using resttemplate
(?). problem is, i'm behind proxy.
this code right now:
simpleclienthttprequestfactory factory = new simpleclienthttprequestfactory(); inetsocketaddress address = new inetsocketaddress(host, 3128); proxy proxy = new proxy(proxy.type.http, address); factory.setproxy(proxy); resttemplate resttemplate = new resttemplate(); resttemplate.setrequestfactory(factory);
seems work, need authenticate @ proxy, how done? proxy
type simpleclienthttprequestfactory
type don't seem handle credentials. without credentials, i'm getting 407...
after quite few different options settled on below code due ability set proxy resttemplate @ creation refactor separate method. note has additional dependency keep in mind.
private resttemplate createresttemplate() throws exception { final string username = "myusername"; final string password = "mypass"; final string proxyurl = "proxy.nyc.bigtower.com"; final int port = 8080; credentialsprovider credsprovider = new basiccredentialsprovider(); credsprovider.setcredentials( new authscope(proxyurl, port), new usernamepasswordcredentials(username, password)); httphost myproxy = new httphost(proxyurl, port); httpclientbuilder clientbuilder = httpclientbuilder.create(); clientbuilder.setproxy(myproxy).setdefaultcredentialsprovider(credsprovider).disablecookiemanagement(); httpclient httpclient = clientbuilder.build(); httpcomponentsclienthttprequestfactory factory = new httpcomponentsclienthttprequestfactory(); factory.sethttpclient(httpclient); return new resttemplate(factory); }
//dependencies used.
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.2</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-web</artifactid> <version>4.2.5.release</version> </dependency>
Comments
Post a Comment