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?
 
CEHJConnect With a Mentor Commented:
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
 
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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
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
 
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:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.