• December 22, 2024

Java Proxy Authentication Example

Authenticated HTTP proxy with Java – Stack Overflow

Most of the answer is in existing replies, but for me not quite. This is what works for me with (I have tested all the cases with JDK 7 and JDK 8). Note that you do not have to use the Authenticator class.
Case 1: Proxy without user authentication, access HTTP resources
oxyHost=myproxy oxyPort=myport
Case 2: Proxy with user authentication, access HTTP resources
oxyHost=myproxy oxyPort=myport oxyUser=myuser oxyPassword=mypass
Case 3: Proxy without user authentication, access HTTPS resources (SSL)
Case 4: Proxy with user authentication, access HTTPS resources (SSL)
Case 5: Proxy without user authentication, access both HTTP and HTTPS resources (SSL)
oxyHost=myproxy oxyPort=myport oxyHost=myproxy oxyPort=myport
Case 6: Proxy with user authentication, access both HTTP and HTTPS resources (SSL)
oxyHost=myproxy oxyPort=myport oxyUser=myuser oxyPassword=mypass oxyHost=myproxy oxyPort=myport oxyUser=myuser oxyPassword=mypass
You can set the properties in the with tProperty(“key”, “value) too.
To access HTTPS resource you may have to trust the resource by downloading the server certificate and saving it in a trust store and then using that trust store. ie
tProperty(“”, “c:/temp/cert-factory/my-cacerts”);
tProperty(“”, “changeit”);
Proxy Authentication for Java - Nashua Silver Knights

Proxy Authentication for Java – Nashua Silver Knights

Proxy Authentication
If you access the Internet from behind a firewall, the connection�s
Proxy Authorization property has to be set. The ways to set the proxy
property differ between HTTP protocol and HTTPS protocol. Since HTTP protocol
is not utilized with UPS OnLine Tools, the HTTPS protocol implementation
will be detailed below using both SSLite and JSSE.
HTTPS Protocol
Code Examples
The following code example illustrates an implementation using SSLite:
tProperties()(“oxyHost”,
proxy);
tProperties()(“oxyPort”,
port);
// do
this anytime system properties have been related to HTTPS handler
();
// Setup
proxy authentication (new
Proxy(username, password));
Class Proxy implements the interface of
The source code of Proxy is here.
The following code example illustrates an implementation using JSSE:
proxy authentication
(new PasswordAuthenticator());
PasswordAuthenticator
class is defined as the following:
import;
class
PasswordAuthenticator extends Authenticator {
protected
PasswordAuthentication getPasswordAuthentication() {
(“getPasswordAuthentication()
called for connection!!! “);
return
new PasswordAuthentication(strUser, “password”. toCharArray());}}
JDK version
1. 2. 1 or greater is required for the class
Here
is the completed source code of the class XmlTransmitter, which handles
reading the XML request file, sending the request to UPS Online Tool server,
and writing the XML response to a file. This class uses SSLite for Java
1. 1. x. In order for the sample code to function, the
file must be added to the client machine’s class path. Included with the
is the file named
that must be used for a successful SSLite implementation. It is recommended
that you follow the examples provided by your particular SSL package when
implementing the respective code.
If you already have an XML request file and want to have the XML response
write to a file, you can run XmlTransmitter
. The configuration file sets the server’s
host name, connection protocol, location of the file, and
proxy server properties. A sample configuration file is here.
You can
modify the values based on your application.
Please refer to “Working with Java
Sample Code” before executing or compiling and source code found
within this documentation.
Return to Top
Copyright
� 2006 United Parcel Service of America, Inc.
java.net.Authenticator java code examples | Tabnine

java.net.Authenticator java code examples | Tabnine

Best Java code snippets using (Showing top 20 results out of 2, 196)Refine searchCommon ways to obtain Authenticatorprivate void myMethod () {}@Test
public void testUserPassword() throws Exception {
startServer(buildUserPasswordConfig());
tDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(“oryx”, “pass”. toCharArray());}});
try {
String response = String(
new URL(“localhost:” + getHTTPPort() + “/helloWorld”),
StandardCharsets. UTF_8);
assertEquals(“Hello, World”, response);} finally {
tDefault(null);}}
InetSocketAddress proxyAddress = (InetSocketAddress) dress();
auth = (
tHostName(), getConnectToInetAddress(proxy, url), tPort(),
(), (), (), (), );} else {
(), getConnectToInetAddress(proxy, url), (), (),
(), (), (), );
tUserName(), new String(tPassword()), arset());
return wBuilder()
(proxyAuthorization? “Proxy-Authorization”: “Authorization”, credential)
public PasswordAuthentication getPasswordAuthentication() {
if ((getRequestingHost()) || getRequestorType()()) {
(“Using the configured proxy username and password”);
if (tBoolean(, true)) {
tProperty(“”, “”);}} catch (InvalidSettingException ex) {
(“This exception can be ignored”, ex);}
return new PasswordAuthentication(username, CharArray());}
return tPasswordAuthentication();}};
log(“Proxy AuthUser: ” + proxyAuthUser);
log(“Proxy AuthPassword: ” + proxyAuthPassword);
protected PasswordAuthentication
final Proxy proxy = new Proxy(, InetSocketAddress. createUnresolved(proxyHost, proxyPort));
if(DEBUG){
log(“Opening proxied connection(” + proxyHost + “:” + proxyPort + “)”);
con = (HttpURLConnection) new URL(url). openConnection(proxy);} else {
con = (HttpURLConnection) new URL(url). openConnection();
tConnectTimeout(connectionTimeout);
tReadTimeout(readTimeout);
private void postJobUpdate(String storyName, SessionId sessionId, String payload) {
URL url = new URL(” + getSauceUser() + “/jobs/” + String());
return new PasswordAuthentication(getSauceUser(), getSauceAccessKey(). toCharArray());}});
HttpURLConnection connection = (HttpURLConnection) Connection();
tDoOutput(true);
tRequestMethod(“PUT”);
OutputStreamWriter writer = new OutputStreamWriter(tOutputStream());
(payload);
();
int rc = tResponseCode();
String jobUrl = null;
if (rc == 200) {
jobUrl = readResponseLinesFromSauceLabToGetJobUrl(new BufferedReader(new InputStreamReader(tInputStream())));
(storyName, jobUrl);}} catch (IOException e) {
(“SauceContextStoryReporter: Error updating Saucelabs job info: ” + tMessage());}}…
URL url = new URL(urlString);
(“Reading… ” + url);
tDefault(new ProxyAuthenticator(“username”, “password”);
SocketAddress addr = new InetSocketAddress(“”, 80);
Proxy proxy = new Proxy(, addr);
HttpURLConnection conn = (HttpURLConnection)Connection(proxy);…
InputStream getAuthenticatedResponse(final String urlStr, final String domain, final String userName, final String password) throws IOException {
return new PasswordAuthentication(
domain + “\\” + userName, CharArray());}});
URL urlRequest = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) Connection();
tDoInput(true);
tRequestMethod(“GET”);
tRequestProperty(“Accept”, “*/*”);
return tInputStream();}
public static void main(String[] args) throws IOException {
tProperty(“oxyHost”, “proxy. ***”);
tProperty(“oxyPort”, “####”);
Authenticator authenticator = new Authenticator() {
return (new PasswordAuthentication(“user”,
“pwd”. toCharArray()));}};
tDefault(authenticator);
URL url = new URL( “localhost:8080/ImageCanvas/Servlet2”);
BufferedReader br = new BufferedReader(new InputStreamReader(Stream()));
String line;
while((adLine())! = null){
(line);
();}
HttpConfiguration clientConfiguration) throws IOException {
= clientConfiguration;
URL url = new URL(());
Proxy proxy = null;
String proxyHost = ();
int proxyPort = ();
if ((proxyHost! = null) && (proxyPort > 0)) {
SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
proxy = new Proxy(, addr);
nnection = (HttpURLConnection) Connection(proxy);} else {
nnection = (HttpURLConnection) url. openConnection(_PROXY);
Authenticator authenticator = new DefaultPasswordAuthenticator(
username, password);
lueOf(()));
tProperty(“”, “true”);
setRequestMethodViaJreBugWorkaround(nnection, tHttpMethod());
tConnectTimeout(());
tReadTimeout(());
tDefault( new Authenticator() {
server = new URL( urlToUse);
URLConnection connection = Connection();
tRequestProperty(
environmentSubstitute( headerName[j]), environmentSubstitute( headerValue[j]));
if ( Debug()) {
tDoOutput( true);
uploadStream = tOutputStream();
fileStream = new BufferedInputStream( new FileInputStream( new File( realUploadFile)));
private YourService proxy;
public YourServiceWrapper() {
final String username = “username”;
final String password = “password”;
username,
CharArray());}});
URL url = new URL(“yourserviceurl/YourService? WSDL”);
QName qname = new QName(“targetnamespace/of/your/wsdl”, “YourServiceNameInWsdl”);
Service service = (url, qname);
proxy = tPort();
Map requestContext = ((BindingProvider) proxy). getRequestContext();
(BindingProvider. ENDPOINT_ADDRESS_PROPERTY, String());
(ERNAME_PROPERTY, username);
(SSWORD_PROPERTY, password);
Map> headers = new HashMap>();
(TP_REQUEST_HEADERS, headers);} catch (Exception e) {
(“Error occurred in web service client initialization”, e);}}
private static String fetchDataFromServer() throws HttpException, IOException, NoSuchAlgorithmException, KeyManagementException {
(“__ENTERING CluemasterData::fetchDataFromServer()”);
URL u = new URL(“);
HttpsURLConnection = (HttpsURLConnection)Connection();
tDefault( new MyAuthenticator());
tAllowUserInteraction(true);
nnect();
InputStream is = tInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = adLine())! = null)
{
(line + “\n”);}
return String();}
catch (HttpException he) {
return null;}
catch (IOException ioe) {
return null;}}
URL url = null;
url = new URL(urlStr);} catch (MalformedURLException e) {
throw new Exception(“Malformed URL”, e);}
HttpURLConnection con = null;
if (user! = null && pass! = null)
return new PasswordAuthentication(user, pass. toCharArray());}});
ustAllHostnames();
ustAllHttpsCertificates();
con = (HttpURLConnection) Connection();
tUseCaches(false);
tRequestProperty(“Content-Type”, ConTypeGet);
(“Execute GET request Content-Type: ”
+ tRequestProperty(“Content-Type”));
(“URL:” + url);
int invokeOperation(String operation) {
tDefault(getAuthenticator());
String urlString = getInvokeUrl() + “&operation=” + operation;
URL invoke = new URL(urlString);
tReadTimeout(getHttpRequestReadTimeout());
InputStream in = tInputStream();
int ch;
while ((ch = ())! = -1) {
((char) ch);}
(“”);
();} catch (final ConnectException e) {
(this, e, “error when attempting to fetch URL \”%s\””””

Frequently Asked Questions about java proxy authentication example

Leave a Reply