Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2008-11-07
9
Medium Priority
?
1,362 Views
Last Modified: 2013-11-23
Hi,
I told that I got my solution for the previous problem from the link http://www.exampledepot.com/egs/java.net/Auth.html
 
In that, it is not mentioned, how to destroy the session, if any.
Kindly say, how to destroy the session .
I ask this for the reason that, even if I give new username and password, I get the output for previous username and password.
When I access it from url and I close the browser, the session is expired. I do not know, how to do it from my code
I have attached the code.
Any help n this regard will be well appreciated with points.
Regards,
Seejith
package booodrive;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.lynxoft.dld.utils.UtilsHTTPS;
 
public class GetAuthenticatedData
{
	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 static String sendRequestString(String api)
	{
	    Authenticator.setDefault(new MyAuthenticator());
	    try {
	        URL url = new URL(api);
	        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	        String str;
	        while ((str = in.readLine()) != null) {
	        }
	        in.close();
	    } catch (MalformedURLException e) {
	    } catch (IOException e) {
	    }
		HttpsURLConnection connection = null;
		connection = sendRequest(api);
		String RecupFile = readBuildRequest(connection);
		System.out.println("recupFile : " + RecupFile);
		connection.disconnect();
		connection =null;
		return RecupFile;
	}
	public static HttpsURLConnection sendRequest(String stringURL)
	{
		HttpsURLConnection connection=null ;
		try{
		URL url = new URL(stringURL);
		connection = (HttpsURLConnection)url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(POST);
		}
		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;
		reader =  new BufferedReader(new InputStreamReader(connection.getInputStream()));
 
			while ((line = reader.readLine()) != null) 
			{
				fileRequest =""+ line;
			}	
 
		}
		catch(MalformedURLException mue) { mue.printStackTrace(); }
		catch(IOException ioe) { ioe.printStackTrace(); }
		
		System.out.println("filerequest"+ fileRequest);
		return fileRequest;
	}
	public static void main(String args[]){
		GetAuthenticatedData ut = new GetAuthenticatedData();
		final	String currRep = "/"+"kklop"; 
		System.out.println("vre"+ut.sendRequestString("https://" + UtilsHTTPS.username +":"+ UtilsHTTPS.password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}"));
	}
}
class MyAuthenticator extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
        String promptString = getRequestingPrompt();
        String hostname = getRequestingHost();
        InetAddress ipaddr = getRequestingSite();
        int port = getRequestingPort();
 
        String username = UtilsHTTPS.username;
 
        String password = UtilsHTTPS.password;
 
        return new PasswordAuthentication(username, password.toCharArray());
    }
}

Open in new window

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

Expert Comment

by:CEHJ
ID: 22903442
I don't know what that lynxoft stuff is, but it's not authenticating you in that routine.

You can't control the session from your end, particularly, with a 'home brew' implementation of http

Personally, I wouldn't attempt to do this on that target site without the use of a specialised API such as Apache HttpClient
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22903444
Oh and that target URL looks dodgy too - you should URLEncode the parameters
0
 

Author Comment

by:Sreejith22
ID: 22928149
Hi CEHJ,
I have modified my question as given below. Can you be bit more precise as to what to do.


The attached code works fine for me. When I access the url("address" in the code), with the given username and password, it gives me the output which I need.
The problem is that, when I give another username and password, it gives me the output corresponding to previous username and password(ie; if I give username and password as 'a','a' for the first time it gives me correct output corresponding to 'a','a'. After that when I give the username and password 'b', 'b' , it gives me the output corresponding to 'a', 'a').
How can I overcome this?



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import com.lynxoft.dld.utils.UtilsHTTPS;
 
public class GetAuthenticatedData
{
	public static String sendRequestString(String address)
	{
	    Authenticator.setDefault(new MyAuthenticator());
	    String str = null;
	    try {
	        URL url = new URL(address);
	        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	        
	        while (( str = in.readLine()) != null) {
	        	System.out.println("string returned by server is "+str);
	        	return str;
	        }
	        in.close();
	    } catch (MalformedURLException e) {
	    } catch (IOException e) {
	    }
	    Authenticator.setDefault(null);
		return str;
	}
}
class MyAuthenticator extends Authenticator {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(UtilsHTTPS.username, UtilsHTTPS.password.toCharArray());
    }
}

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 86

Expert Comment

by:CEHJ
ID: 22934730
Does the behaviour differ in a browser?
0
 

Author Comment

by:Sreejith22
ID: 22937001
Yes it works correctly from a browser.

Even if I manually change the value of username and password and execute the code using public static void main, it works perfectly. But, I really do not know why this problem occurs when I use this code from the application.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22938697
I would check out the headers sent with and without a browser. You need to use some kind of proxy for that. Try Java 'Charles'
0
 

Author Comment

by:Sreejith22
ID: 22938861
CEHJ,
I almost found out what the mistake is.
In my code given, please note the line

>>Authenticator.setDefault(new MyAuthenticator());

Authenticator is an abstract class and setDefault is a static method.

No matter how many times I call the method sendRequestString(String address) , the setDefault method is called once and only once.

How can I get around this problem, such that, each time I call the method sendRequestString(String address), the method Authenticator.setDefault(new MyAuthenticator()); should work all the time.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 22938951
Oh yes, you don't need or want to keep setting the Authenticator. All you need to do is to change the credentials returned by the instance, not the instance of the Authenticator itself
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22948436
:-)
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 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