0

I have a usecase where I have a set of HTTPS GET requests which are password protected, I want to access the Request body but without passing username/password everytime, instead using the my Chrome browser session.

Here is how I am trying by creating new HTTP connection everytime giving my credentials, which is not suggestible and also slow.

String url = "<Request URL>";
URL obj = new URL(url);

String encoding = Base64.getEncoder().encodeToString(("<username>:<password>").getBytes());
System.out.println("Encoded Credential String:==>"+encoding);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setRequestProperty  ("Authorization", "Basic " + encoding);

System.out.println("Response connection string: "+con.toString());

BufferedReader in = new BufferedReader(
        new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());

Can someone please provide me directions, how I should proceed if my implementation is in Java ?

Om Sao
  • 7,064
  • 2
  • 47
  • 61
  • How do you authorize? Its seams you want to authorize via basic Auth? Is the server supporting authorization via basic auth? Or do you want to use cookies? Please explain, what excaclty you are up to do – YingYang Jun 06 '18 at 07:20
  • @YingYang: I want to use cookies, as I understand that Basic Auth is not reliable and suggested. – Om Sao Jun 06 '18 at 09:10
  • You only want to send a cookie to the authendicate server, or do you first have to authorize and receive a cookie? For sending, have a look here: https://stackoverflow.com/questions/12761273/how-to-send-a-cookie-in-a-urlconnection To receive, you have to use "getHeaderFieldKey" See here: http://java2s.com/Tutorials/Java/URL_Connection_Address/Get_and_set_cookie_through_URLConnection_in_Java.htm – YingYang Jun 06 '18 at 09:20
  • is it a pure java or an android application? – YingYang Jun 06 '18 at 09:31

1 Answers1

0

Using basic auth is really not any "slower" in any meaningful sense.

However, If you want to use cookies then you can just do

urlConn.setRequestProperty("Cookie", "cookiename=cookievalue");

instead of Authorization header you currently have. This is assuming you know the cookie name and value to send. You can inspect Chrome HTTP traffic to get that.

eis
  • 51,991
  • 13
  • 150
  • 199