Java HttpURLConnection - POST with Cookie - java

I´m trying to send a post request with cookies. This is the code:
try {
String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
String cookies = "session_cookie=value";
URL url = new URL("https://myweb");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(query);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
// Send the request to the server
//conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is the request is sent without the cookies. If I only make:
conn.connect(); and don´t send data, the cookies are sent OK.
I can´t check exactly what is happening, because the connection is thorugh SSL. I only check the response.

According to the URLConnection javadoc:
The following methods are used to access the header fields and the
contents AFTER the connection is made to the remote object:
* getContent
* getHeaderField
* getInputStream
* getOutputStream
Have you confirmed that in your test case above the request is getting to the server at all? I see you have the call to connect() after getOutputStream() and commented-out besides. What happens if you uncomment it and move up before the call to getOutputStream() ?

Related

Java server side connection with firebase connection timeout

I am trying to connect to firebase to send push notification to an android app.
I have written following code in Java Server side. But I am getting connection timed out exception always.
final String apiKey="AAAAeEpqP-w:APA91bFulyT23Km-onTNr_q5yEz4uoOaM8KdE4LMyIoz6kWlk3pJSHirDJBSiqESRXKiGa-Z_tBfpXA6naaaTXxcFFxAnaSkMTPVVOMswyJ0bhhdpwlo-92HXgxRMsHV6Y8bNaHX7tMd";
int i=0;
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection ) url.openConnection();
System.out.println("after connection open");
//conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
JSONObject json = new JSONObject();
json.put("to", "device-token");
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body");
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
// result = CommonConstants.SUCCESS;
System.out.println("after closed out put stream");
int responseCode = conn.getResponseCode();
// System.out.println("Post parameters : " + input);
System.out.println("Response Code : " + responseCode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
It always shows session timeout error.
Is it a correct way to send notifications to app.
Any help is appreciated.
EDIT :- I have called the same url with device token and other things from rest client and it works well.I got a notification in my app.But when i send it thru Java code at that time it shows connection timed out.
Here's the official Firebase documentation which can help you set up the server. https://firebase.google.com/docs/cloud-messaging/server
In your code I noticed json.put("to", "device-token"); and I am assuming that you are using it as a placeholder only for the example. If not, in your request you need to send a device-token like { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } .

HttpURLConnection: resulting json-code suggests page doesnt exist (404), even when url is correct

I am trying to get data from an MySQL database using a php-file. My java code is as follows:
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(getURL);
System.out.println(getURL);
conn = (HttpURLConnection)url.openConnection();
//conn.setReadTimeout(READ_TIMEOUT);
//conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("user", USER);
builder.appendQueryParameter("pass", PASS);
builder.appendQueryParameter("server", SERVER);
builder.appendQueryParameter("db", DB);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
result = reader.readLine();
return(result);
}else{
return("unsuccessful");
}
When I go to my url (hidden in the variable getURL) using a browser, I see string of json on my screen, just as it should. However, when I output the contents of the reader (above code only takes the first line, but by adapting the code I can, of course, output more) it shows the html-code for a website displaying a 404 - Page does not exist message.
Anyone has any idea what goes wrong? Yes, I did check for typo's.
Okay, I have no clue what happened, as I didn't change anything. But all of the sudden it started working?!?
Must have been something server-side I guess...
Thanks for the input and sharing your thoughts!

Requesting through HTTPURLConnection Transfer-Enconding chunked

I'm trying to get data from a API's endpoint and I have noticed the data I'm trying to get by HTTP POST method is huge and the API's server respond me with a response with one of headers set as Transfer-Encoding: chunked and I'd like to read the whole data. In my code I'm using the java.net.HttpURLConnection to establish my post request and read the data as showed bellow.
Unfortunately for this scenario I'm getting java.io.IOException: Premature EOF at the line where I read from the BufferedReader(while((output = br.readLine()) != null)) I debugged it and I'm getting status http 200 until right before the Exception has been threw.
Is there anything wrong in requesting chunked data like showed in my code?
Thank you.
String responseStr = "";
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(this.url).openConnection();
connection.setRequestProperty("content-type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(payloadToBeRequested.getBytes());
os.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String output = "";
while((output = br.readLine()) != null){
responseStr = responseStr + output;
}
status = connection.getResponseCode();
connection.disconnect();
}catch(MalformedURLException ex){
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}

Simulate URL entering on java

So I have a problem where if I type this link on the browser and hit enter, an activation happens. I just want to do the same through Java. I don't need any kind of response from the URL. It should just do the same as entering the URL on a browser. Currently my code doesn't throw an error, but I don't think its working because the activation is not happening. My code:
public static void enableMachine(String dns){
try {
String req= "http://"+dns+"/username?username=sputtasw";
URL url = new URL(req);
URLConnection connection = url.openConnection();
connection.connect();
/*BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
System.out.println(strTemp);
}*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
What's the problem?
If you want to do that with an URLConnection, it isn't sufficient to just open the connection with connect, you also have to send e.g. an HTTP request etc.
That said, i think it would be easier, if you use an HTTP client like the one from Apache HttpComponents (http://hc.apache.org/). Just do a GET request with the HTTP client, this would be the same as visiting the page with a browser (those clients usually also supports redirection etc.).
You may use HttpUrlConnectionClass to do the job:
URL url = new URL("http://my.url.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("Content-Type", "application/json");
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
String params = "foo=42&bar=buzz";
DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
httpCon.connect();
int responseCode = httpCon.getResponseCode();
You may as well use "GET" request method and just append parameters to the url.

REST HttpURLConnection

I am working on a REST Client experimenting with the tinkerpop database using using HttpURLConnection.
I am trying to send over a 'GET - CONNECT'. Now I understand (from some net research) that if I use doOutput(true) the 'client' will a 'POST' even if I setRequestMethod 'GET' as POST is the default (well ok?) however when I comment out the the doOutput(true) I get this error:
java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:995)
at RestContent.handleGetConnect(RestContent.java:88)
at RestClient.main(RestClient.java:42)`
Here is the communication code snip I have tried various option with setUseDoOutPut().
//connection.setDoInput(true);
connection.setUseCaches (false);
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
// set GET method
try {
connection.setRequestMethod("GET");
} catch (ProtocolException e1) {
e1.printStackTrace();
connection.disconnect();
}
Exception at connection.setRequestMethod("GET") in the other case. Any hints?
Following code works fine: URL is a Rest URL with supported GET operation.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setDoOutput(true);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

Categories

Resources