Solved

Java Exception- "java.io.IOException: Server returned HTTP response code: 401 for URL..."

Posted on 2008-11-03
6
4,899 Views
Last Modified: 2013-11-22
Hi experts,
I have encountered with a problem. I have given my code below. When I run that code, I get the following exception

>>java.io.IOException: Server returned HTTP response code: 401 for URL: https://LOGIN:PASSWORD@www.mybooo.com/core/Dd002wW.php
      at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
      at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
      at GetData.readBuildRequest(GetData.java:98)
      at GetData.sendRequestString(GetData.java:48)
      at GetData.main(GetData.java:118)


When I access it by giving appropriate username and pasword in browser, it works(https://LOGIN:PASSWORD@mybooo.com/core/Dd002wW.php).. But not with this java code. I know this is related to some authentication problem. But how to overcome this?
Any help in this regard will be well appreciated with points.
Warm Regards,
Sreejith

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

 

 

public class GetData

{

	public static final String UTF8_ENCODING = "UTF-8";

	public static String username;

	public static String password;

	private static String urlCheck = "";

	private static final String POST = "POST";

	public String setCSVString(String username, String password)

	{

		String csvString = "";

		//csvString = "{usr:'" + username + "',pwd:'"+password+"'}";

		urlCheck = "https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php";

		System.out.println("This is the csvString"+csvString);

		System.out.println("chaine non encodee : " + csvString);

		return csvString;	

	}

 

	public String setEncodedCSVString(String csvString)

	{

		String encodedCsvString="";

		//try 

		{

			encodedCsvString = URLEncoder.encode("data={action:'contacts',args:''}");// + URLEncoder.encode(csvString, UTF8_ENCODING);

			System.out.println("chaine encodee : " + encodedCsvString);

		} 

		//catch (UnsupportedEncodingException e) { e.printStackTrace();}

		

		return encodedCsvString;

		

	}

	public static String sendRequestString(String encodedCsvString)

	{

		HttpsURLConnection connection = null;

		connection = sendRequest(urlCheck,encodedCsvString);

		

		// Reponse du serveur

		String RecupFile = readBuildRequest(connection);

		

		System.out.println("recupFile : " + RecupFile);

		String recupFileSub = RecupFile.substring(RecupFile.indexOf("'")+1, RecupFile.lastIndexOf("'"));

		//String RecupFileFinal = recupFileSub.replaceAll("\"", "");

		String RecupFileFinal = recupFileSub;

		connection.disconnect();

		connection =null;

		return RecupFileFinal;

	}

	public static HttpsURLConnection sendRequest(String stringURL,String data)

	{

		HttpsURLConnection connection=null ;

		// Creation de la connection

		try{

 

			//String def = URLEncoder.encode(data);

			//log.info("def : " + def);

		URL url = new URL(stringURL);

		connection = (HttpsURLConnection)url.openConnection();

 

	//	URLConnection connection = url.openConnection();

		connection.setDoOutput(true);

		connection.setDoInput(true);

		connection.setRequestMethod(POST);

		

		//envoi de la requête

		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

 

		writer.write(data);

		writer.flush();

		writer.close();

		

		}

		catch(MalformedURLException mue)

		{ 

			mue.printStackTrace(); 

		}

		catch(IOException ioe){ ioe.printStackTrace(); }

		return connection;

	}

	public static String readBuildRequest(HttpsURLConnection connection)

	{

 

		String line;

		String fileRequest=null;

		try

		{

		BufferedReader reader = null;

		//lecture de la réponse

		reader =  new BufferedReader(new InputStreamReader(connection.getInputStream()));

 

		//FileHelper fileHelper = new FileHelper();

			while ((line = reader.readLine()) != null) 

			{

				System.out.println("reader " + line);

				fileRequest =""+ line;

				System.out.println("filerequest"+ fileRequest);

			}	

 

		}

		catch(MalformedURLException mue) { mue.printStackTrace(); }

		catch(IOException ioe) { ioe.printStackTrace(); }

		

		System.out.println("filerequest"+ fileRequest);

		return fileRequest;

	}

	public static void main(String args[]){

		GetData ut = new GetData();

		final	String currRep = "/"+"src.rar"; 

		System.out.println(ut.sendRequestString(ut.setEncodedCSVString(ut.setCSVString("LOGIN","PASSWORD"))));

		//System.out.println(System.getProperties().getProperty("java.home"));

	}

}

Open in new window

0
Comment
Question by:Sreejith22
  • 3
  • 2
6 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 300 total points
ID: 22866389
Try doing the authentication like this:

http://forums.sun.com/thread.jspa?threadID=5094366
0
 
LVL 59

Assisted Solution

by:Kevin Cross
Kevin Cross earned 200 total points
ID: 22866452
You are correct it is authentication related as the 401 status code is the UNATHORIZED status for http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

What you may need to do is pass these values in header versus in URL.  Let me see if I can find an example.
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22866458
Actually that is a good one from CEHJ, I just didn't have my browser refreshed yet.  
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Sreejith22
ID: 22869713
Thanks CEHJ and mwvisa1,
I got the output with http://www.exampledepot.com/egs/java.net/Auth.html

Still, thanks a lot for your valuable help.

Regards,
Sreejith
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 22870298
Glad you found that.  CEHJ posted that link to answer another question along this lines...  Just glad to share in his genius on this occassion. :)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22871136
:-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

One of the typical problems I have experienced is when you have to move a web server from one hosting site to another. You normally prepare all on the new host, transfer the site, change DNS and cross your fingers hoping all will be ok on new server…
Outsource Your Fax Infrastructure to the Cloud (And come out looking like an IT Hero!) Relative to the many demands on today’s IT teams, spending capital, time and resources to maintain physical fax servers and infrastructure is not a high priority.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now