Connect to a password protected URL from Java program

By: Mike Cooper Emailed: 1767 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

It is quite common for a Java program to connect to an URL and process its data or post data to it. Some URLs are password protected and can be connected to it only with a username and password. While manually accessing such sites, the browser will popup a login screen automatically for the user to key in username and password. But if you are connecting from a Java program then how can you do this login programmatically.

This sample Java program connects to password protected URL. The three arguments for this application is the password protected url to connect to, the username and the password. Take note that the System properties to set the proxy has to be changed to suit your own network proxy settings. If your network doesn't need a proxy then just set the proxy to false.

import java.io.*;
import java.net.*;
import java.util.*;
public class postto{

private void fetchURL (String urlString,String user,String pass) {

try {
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;

Properties sysProperties = System.getProperties();

sysProperties.put("proxyHost", "proxy.cyberway.com.sg");
sysProperties.put("proxyPort", "8080");
sysProperties.put("proxySet", "true");
url = new URL (urlString);
urlConn = url.openConnection();
urlConn.setDoInput (true);

urlConn.setDoOutput (true);

urlConn.setUseCaches (false);

urlConn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");

printout = new DataOutputStream (urlConn.getOutputStream ());

String content = "USERNAME=" + URLEncoder.encode (user) + "&PASSWORD=" + URLEncoder.encode (pass);

printout.writeBytes (content);
printout.flush ();
printout.close ();

input = new DataInputStream (urlConn.getInputStream ());
FileOutputStream fos=new FileOutputStream("postto.txt");
String str;
while (null != ((str = input.readLine())))
{

if (str.length() >0)
{
fos.write(str.getBytes());
fos.write(new String("\n").getBytes());
}
}
input.close ();
}
catch(MalformedURLException mue){ System.out.println (mue);}
catch(IOException ioe){ System.out.println (ioe);}
}
public static void main (String args[]) {
postto au=new postto();
au.fetchURL(args[0],args[1],args[2]);
}
}

Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(6)


1. View Comment

Thanks for the help, however I am having some difficulty implementing it.
I keep getting the following:
java.io.IOException: Server returned HTTP response code: 403 for URL: ...

I have tried this on two different urls and I always get the same.

I tried setting it like so:
sysProperties.put("proxySet", "false");

but still I get the error - can you offer any advice?

Also Java tells me that
URLEncoder.encode and
input.readLine

are deprecated - is there an easy alternative?

Thank you very much in advance.


View Tutorial          By: Andrew at 2008-09-30 14:51:14
2. View Comment

i want to know how to connect one page to another page program using java program i needed will you provide one example program with connectivity you can send to my mail id

View Tutorial          By: mahesh at 2009-08-26 01:31:40
3. View Comment

Hi Andrew,

I have a java application which users are authentication using their credentials. I have link this application, which will redirect to .Net application. I want pass the userid and password to this appliaction for validatation from java application. Is there any way using above code to achive this functionality

Thanks,
Kumar


View Tutorial          By: kumar at 2010-10-06 10:42:55
4. View Comment

Thanks a lot for sharing this solution.

View Tutorial          By: Bharath at 2012-12-18 18:32:33
5. View Comment

Hey thanks for your tutorial.

But if i had a Site with a security answer, how to implement this? How to send the answer of the security question to the validation address of the specific site?


View Tutorial          By: Matze at 2013-07-19 16:08:46
6. View Comment

Hey thanks for your tutorial. But i'm getting an error when i run it.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at postto.main(postto.java:57)

(in 57.line there is this line : au.fetchURL(args[0],args[1],args[2]);

i'm looking for a solution for this but i couldn't solve this, can you help me at this?


View Tutorial          By: acc at 2013-07-25 14:30:50

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Mike Cooper
Connect to a password protected URL from Java program

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
A Serialization Example in Java
Type Casting in Java
instanceof sample program in Java
Using One-Dimensional Arrays in Java
Method Overriding in Java
indexOf( ) and lastIndexOf( ) in Java
The java Buzzwords
Write to a file in Java - Sample Program
XML and Java - Parsing XML using Java Tutorial
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Java program to check if user input is an even number
HTTPS Java - URL Connection program. Using HttpsURLConnection
Most Emailed Articles (in Java)
Converting a number into its equalant value in words in Java
java.lang.reflect package
Disadvantages of using Native methods in Java
What is UCS? What is ISO 10646?
Generating Your Key Pair example using keytool in Java
Operator Precedence in Java
PushbackReader sample program in Java
concat(), replace(), and trim() Strings in Java
instanceof sample program in Java
Use of - new - in Java
The Benefits of OOP
Increment and Decrement Operator
Characters in java
The continuing Revolution of java
Why java is important to the Internet