HTTPUrlConnection maintain session - java

I am using Restful Services on server and trying to maintain the same session after performing login:
URL endpoint = new URL(getString(R.string.url_login));
// Create connection
HttpURLConnection myConnection = (HttpURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");
// Create the data
String myData = "username=" + username + "&password=" + pwd;
// Enable data writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
rc = myConnection.getResponseCode();
if (rc == 200) {
String Cookie= myConnection.getHeaderField("Set-Cookie");
URL endpoint2 = new URL(getString(R.string.url_checkUserType));
HttpURLConnection myConnection2 =
(HttpURLConnection)endpoint2.openConnection();
myConnection2.setRequestMethod("GET");
myConnection2.setRequestProperty("User-Agent", "my-rest-app-v0.1");
myConnection2.setRequestProperty("Cookie", Cookie);
rc2 = myConnection2.getResponseCode();
....
}....
The problem is that rc2 is every time 401 as WebService doesn't recognize that requiest is part of the same session. What am I doing wrong?

You may do as follows
on the server side, it checks if the incoming request has a "sessionId" in cookie: if not, create one and return it in response; if yes, it knows the request belongs to a known session
on the client side, after a successful login, retrieve the "sessionId" from the response, and set it in the following requests
==
connection.setRequestProperty("Cookie", "JSESSIONID=" + URLEncoder.encode(jSessionId, "UTF-8"));

The solution was to use Spring RESTful services for Android that worked great for me.

Related

cURL + Java -- CPAS Request -- Suggestion Please

Explination
I am working on a Java App that sends a text message via a CPAS API (Similar to Tweepy). I am using CURL to request the message send. The request from Java seems to be sent but I am getting a 401 code. I'm assuming there is an issue with the encoding of my Authentication for the request. The code is as follows:
URL url = new URL("https://api.zang.io/v2/Accounts/ACe1889084d37de951ef064200aecbe4b2/SMS/Messages");
String auth = AUTH + ":" + TOKEN;
String encodeedAuth = Base64.getEncoder().withoutPadding().encodeToString(auth.getBytes());
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Authorization", "Basic " + encodeedAuth);
String data = "From=+14132698029&To=17817381451&Body=New Test";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
"""
An HTTP 401 response is commonly an HTTP endpoint authorization failure. The best way to see why your auth credentials are failing is to capture the request/response pair in transit (at the receiving end would be optimal) and then compare that request/response pair to one that works.

Authentication Details Not Provided REST API POST Request

I'm posting to an API server and I'm getting the following reply:
Server Response: {"detail":"Authentication credentials were not provided."}
I'm writing the requests in Java and I'm not sure exactly why it's saying credentials were not provided.
Here is a snippet of my code:
hconn.setRequestProperty("Content-Type", "application/json");
hconn.setRequestProperty( "Accept", "application/json" );
if( urlconn instanceof HttpsURLConnection )
{
String encoded = new String(Base64.getEncoder().encode( ( username + ":" + password).getBytes()));
String auth = "Basic " + encoded;
urlconn.setRequestProperty("Encoded Authorization", auth );
}
Where hconn is of type HttpURLConnection
This is the only relvant snippet that you guys need. Are there properties i'm missing to set here?
I know the server response is from a Django framework but the documentation is not clear on spotting what IS required to prevent this.
Any help appreciated.
Authorization is the correct request header name and not 'Encoded Authorization'. So, you should set
urlConn.setRequestProperty("Authorization", auth);

how to get odata.nextlink from the returned json object in java and call the odata.nextlink url

Currently I'm using
HttpSession session = (HttpSession) request.getSession();
AuthenticationResult result = (AuthenticationResult) session.getAttribute(AuthHelper.PRINCIPAL_SESSION_NAME);
String accessToken = result.getAccessToken();
String tenant = session.getServletContext().getInitParameter("tenant");
url = new URL("https://graph.windows.net/" + tenant + "/users/" + result.getUserInfo().getUniqueId()
+ "/memberOf?api-version=1.6");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Set the appropriate header fields in the request header.
con.setRequestMethod("GET");
con.setRequestProperty("api-version", "1.6");
con.setRequestProperty("Authorization", "Bearer " + accessToken);
con.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
jsonResponse = HttpClientHelper.getResponseStringFromConn(con, true);
which returns the groups which the user belongs to. It is limited to 100 and I'm getting the odata.nextlink. I currently don't know how to use that and recall the graph api to fetch the next set of 100
Please help!!
Or is there any way to increase the limit of response to be greater than 100?
Usually, the odata.nextlink would show like : directoryObjects/$/Microsoft.DirectoryServices.User/b202e3e2-ead2-4878-8f77-81889ce30989/memberOf?$skiptoken=X'445370740900010000000000000000140000005948A9EA0D7571449DAAEF76844271C101000000000000000000000000000017312E322E3834302E3131333535362E312E342E32333331020000000000018020591539727941B538A64692E459E9'
Then, you just need to generate a new request url as: new URL("https://graph.windows.net/" + tenant + "/" +odata.netlink + "&api-version=1.6");
Then, just make another request with Authorization header.
Thanks.

How can I browse web site after login using https/http protocol(in Java)

I'm trying to login web site using Java and I succeeded. Below is the code I used.
String query = "myquery";
URL url = new URL(loginUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
DataInputStream input = new DataInputStream( con.getInputStream() );
for( int c = input.read(); c != -1; c = input.read() ) {
System.out.print( (char)c );
// this page returns JavaScript code
}
After this, I want to access another web page in same domain, so I tried below code.
URL url = new URL(anotherUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
... similar to above code ...
But this page asks me to login again. I think connection has been disconnected in the process of changing URL. (Onlt login page uses HTTPS protocol and other pages use HTTP protocol)
How can I fix this?
Someone please help
Keep in mind that HTTP is completely stateless. The idea of "logging in" to a site translates to (usually) setting cookies from an HTTP perspective. Those cookies are simply HTTP headers and they are sent with each subsequent request by your browser. So for you to maintain the logged in state its up to you get the cookies from the response headers and send them along with future requests.
Here is how:
Retrieving cookies from a response:
Open a java.net.URLConnection to the server:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();
Loop through response headers looking for cookies:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
...
Extract cookie name and value from cookie string:
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg" or "userId=igbrown"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
Setting a cookie value in a request:
Values must be set prior to calling the connect method:
URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
Create a cookie string:
String myCookie = "userId=igbrown";
Add the cookie to a request:
Using the
setRequestProperty(String name, String value);
method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.
urlConn.setRequestProperty("Cookie", myCookie);
Send the cookie to the server:
To send the cookie, simply call connect() on the URLConnection for which we have added the cookie property:
urlConn.connect()

Keep Authentication between different calls to java.net.URL

I have a remote server that use basic authentication (HTTP) and i need several calls to different URLs. A example of calling:
URL address = new URL ("hhtp://localhost:8080");
HttpURLConnection connection;
// open connection
connection = (HttpURLConnection) address.openConnection();
String encoding = DatatypeConverter.printBase64Binary((username + ":" + password).getBytes());
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + encoding);
// transform result code into an exception
int code = connection.getResponseCode();
if ((code < 200) || (code >= 300))
{
throw new HttpRetryException(connection.getResponseMessage(), code, address.toString());
}
return connection;
The problem appear that the server take a lot of time authenticating the user. After this first call, we need another page (a different URL) to the same server. How I can keep the session between different calls?
Edit:
A clarification, I'm trying to connect to a Jenkins server.

Categories

Resources