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

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

Sreejith22Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
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
CEHJCommented:
Oh and that target URL looks dodgy too - you should URLEncode the parameters
0
Sreejith22Author Commented:
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
The Five Tenets of the Most Secure Backup

Data loss can hit a business in any number of ways. In reality, companies should expect to lose data at some point. The challenge is having a plan to recover from such an event.

CEHJCommented:
Does the behaviour differ in a browser?
0
Sreejith22Author Commented:
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
CEHJCommented:
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
Sreejith22Author Commented:
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
CEHJCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
:-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.