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.
Related
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.
We develop mobile applications using ionic framework in the client side and rest webservices in server side. From client side, I 'm able to connect with mfp server successfully.
Now I'm trying to connect my web services server with mfp server for sending pushnotifications . But I am getting 405 error.This is the code I have written
URLConnection connection = new URL("http://localhost:9441/mfp/api/az/v1/token").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("grant_type", "client_credentials");
connection.setRequestProperty("scope", "messages.write");
connection.setRequestProperty("scope", "push.application.com.ionicframework.example854621");
InputStream response = connection.getInputStream();
System.out.println("response"+response);
This is the response I'm getting
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL: http://180.151.63.116:9441/mfp/api/az/v1/token
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at com.sai.laps.webservice.server.authentication.mfp.main(mfp.java:24)
Where am I going wrong? How can I connect my rest web service server with MFP server?
Any help will be appreciated!
In this case, first I 'ld suggest not to use connection.getOutputStream(). This will create issue.
Next, Please test the connection if it is connecting or not.
You have to add Authorization parameter in setRequestProperty
Yes, I remember, I too have faced the same issue due to some certificate error and I had to import the certificate in Java level and after that it worked. (Although I faced some other challenge (Multiple connection) issue afterwards, but that too worked...see here)
Anyways, you try the below code and if it is yet not connecting, please share the exception message
String wsURL = "https://hostservername:postnumber";
String wsUserName = "someUserName";
String wsPassword = "somePassword";
try{
String authString = wsUserName+":"+wsPassword;
byte[] byteAuthStr = authString.getBytes();
String authBase64Str = Base64.encode(byteAuthStr);
System.out.println(authBase64Str);
URL url = new URL(wsURL);
URLConnection conn = url.openConnection();
HttpURLConnection connection = (HttpURLConnection)conn;
connection.setDoOutput(true);
/*connection.setRequestMethod("GET");
connection.setRequestMethod("POST");*/
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic "+authBase64Str);
connection.connect();
System.out.println( connection.getResponseCode());
boolean connected = false;
switch (connection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
System.out.println(url + " **OK**");
connected = true;
break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
System.out.println(url + " **gateway timeout**");
break;// retry
case HttpURLConnection.HTTP_UNAVAILABLE:
System.out.println(url + "**unavailable**");
break;// retry, server is unstable
default:
System.out.println(url + " **unknown response code**.");
break ; // abort
}
}catch(Exception ex){
System.err.println("Error creating HTTP connection");
System.out.println(ex.getMessage());
}
}
I've a problem to login to a website via https.
I wrote this code (it works) for http access:
String user = user;
String password = psw;
String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
URLConnection connection= url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.connect();
I'd like to do the same things but via https. Is it possible?
You can, please use HttpsURLConnection
Checkout sample program on http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/
When specifying your URL, make sure to pass "https://..."
url.openConnection();
will return you an object that has the type of the established connection. It will always be URLConnection, but it can be a class that extends URLConnection as well. Such classes are HttpURLConnection and HttpsURLConnection (and others).
You should verify that the returned object is of type HttpsURLConnection. And if it's not, you should stop the connection (in case you want to avoid non secure connections).
if (connection instanceof HttpsURLConnection)
I have some working java code which does the following:
URL myUrl = new URL("http://localhost:8080/webservice?user=" + username + "&password=" + password + "&request=x");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// code continues to read the response stream
However, I noticed that my webserver access log contained the plaintext password for all of the users who connected. I would like to get this out of the access log, but the webserver admins claim that this needs to be changed in my code and not via webserver config.
I tried changing the code to the following:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
// start of new code
myConnection.setDoOutput(true);
myConnection.addRequestProperty("username", username);
myConnection.addRequestProperty("password", password);
myConnection.addRequestProperty("request", "x");
// code continues to read the response stream
Now the access log does not contain the username/password/request method. However, the webservice now throws an exception indicating that it didn't receive any username/password.
What did I do wrong in my client code? I also tried using "setRequestProperty" instead of "addRequestProperty" and it had the same broken behavior.
I actually found the answer in another question on stackoverflow.
The correct code should be:
URL myUrl = new URL("http://localhost:8080/webservice");
HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(myConnection.getOutputStream ());
wr.writeBytes("username=" + username + "&password="+password + "&request=x");
// code continues to read the response stream
I have java related question...
Website www.stationv3.com gets updated daily (most of the time at least, it's kinda irregular). Every time I connect to a site using address www.stationv3.com (using a browser), it redirects me to it's subpage www.stationv3.com/date_of_latest_update.html
I'm trying to make a program that will pull latest comic from the site, but I am not sure how to find out it's exact address. But I know I'd be able to find out if I could somehow find out where where am I being redirected on every connect. Is that possible with java? I know it can do all sorts of quirky things, but I'm still new to internet related stuff...
I used exact site name just to make it easy for you to check outwhat's going on...
And also, I'm creating a generic code, one which could (with some tinkering) be applyed to any site that functions in that manner.
import java.net.*;
public class ShowStationV3Redirect {
public static void main(String[] args) throws Exception {
URL url = new URL(args[0]);
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
System.out.println("Response code = " + connection.getResponseCode());
String header = connection.getHeaderField("location");
if (header != null)
System.out.println("www.stationv3.com redirected to " + header);
}
}
The above code snippet tells you what URL you are being redirected to.
I think you could just fecth:
http://www.stationv3.com/comics/{yyyy}{mm}{dd}sv3.gif
and forget about the redirection problem. You can use this code (not tested indeed):
URL server = new URL("<put here the image URL>");
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.addRequestProperty("Accept","image/gif");
connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
connection.connect();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream("c:/mycomic.gif");
byte[] buffer = new byte[1024];
int byteReaded = is.read(buffer);
while(byteReaded != -1)
{
os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
}
os.close();