Java class will not compile - java

I am getting a couple errors I cannot seem to fix... This is example code, so I'm confused what's going on. The error's are commented to the side of the lines where they show up.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class Connect {
URL url;
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;
// Build request body
String body = "fname=" + URLEncoder.encode("Atli", "UTF-8"); //Syntax error on token ";", { expected after this token
// Create connection
url = new URL("http://192.168.1.68/test/POST/post.php");
urlConnection = url.openConnection();
((HttpURLConnection)urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", ""+ body.length());
// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
inStream = new DataInputStream(urlConnection.getInputStream());
// Send request
outStream.writeBytes(body);
outStream.flush();
outStream.close();
// Get Response
// - For debugging purposes only!
String buffer;
while((buffer = inStream.readLine()) != null) {
System.out.println(buffer);
}
// Close I/O streams
inStream.close();
outStream.close();
}
giving an error of:
Syntax error, insert "}" to complete ClassBody
Anybody see something obvious that I don't?
On a side note, if the php echoes back html code, upon running this class, is java capable of understanding the html code?

You can't put code directly in the class body - you have to wrap it inside a member function.
If this is intended to be a standalone program that member function should be:
public static void main(String[] args) {
...
}

If you want that code to be executed on construction of an instance of "Connect" you should put it in the constructor. This also fixes all of your errors.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
public class Connect {
URL url;
URLConnection urlConnection;
DataOutputStream outStream;
DataInputStream inStream;
#SuppressWarnings("deprecation")
public Connect() {
// Build request body
try {
String body = "fname=" + URLEncoder.encode("Atli", "UTF-8");
// Create connection
url = new URL("http://192.168.1.68/test/POST/post.php");
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", "" + body.length());
// Create I/O streams
outStream = new DataOutputStream(urlConnection.getOutputStream());
inStream = new DataInputStream(urlConnection.getInputStream());
// Send request
outStream.writeBytes(body);
outStream.flush();
outStream.close();
// Get Response
// - For debugging purposes only!
String buffer;
// DataInputStream.readLine is deprecated
// use the BufferedReader class instead
while ((buffer = inStream.readLine()) != null) {
System.out.println(buffer);
}
// Close I/O streams
inStream.close();
outStream.close();
} catch (IOException iOException) {
// there are many methods that can throw errors in this code,
// you should catch those errors
}
}
}

Related

How to resolve: Server redirected too many times?

Looked through stackoverflow for resolutions, and found this but that didn't help.
Getting this exception
java.net.ProtocolException: Server redirected too many times (20)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
at GetMailStatus.main(GetMailStatus.java:27)
for this block of code that's trying to access an InformedDelivery url with credentials
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Base64;
public class GetMailStatus {
public static void main(String[] args) {
try {
URL url = new URL ("https://informeddelivery.usps.com/.........");
String encoding = Base64.getEncoder().encodeToString(("xxxx:yyyy").getBytes("UTF-8"));
CookieManager msCookieManager = new java.net.CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(msCookieManager);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in =
new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
The code was modified based on the referenced stackoverflow discussion. I'm assuming I'm still not managing cookies correctly. Any suggestions?

Why isn't my outputstream in Java being read/received by my PHP file

I'm trying to perform a simple query in PHP which takes parameters from a Java class. The Java Class is part of an Android phone app I am working on. I am able to make a connection and receive an input stream from the PHP file, which I have been using to see the exact error that my app receives. The error is "Undefined index: username".
I have tested the PHP file by typing the parameters directly into the URL, which has worked, and using a URL with the parameters hard-coded in also works. However, I want to perform different queries, not the same one every time, so I need to be able to pass my parameters in my output stream.
Here is my code:
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
import android.widget.TextView;
public class LoginSupport extends AsyncTask<String, Void, String>{
private TextView progress;
public LoginSupport(TextView progress) {
this.progress = progress;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
try {
//get login values
String username = arg0[0];
//add login values to string
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
//pass login values to PHP file
String urlString = "http://192.**.**.**/App.php?"; //IP address hidden
URL urlForLogin = new URL(urlString);
URLConnection UrlConn = urlForLogin.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) UrlConn;
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setAllowUserInteraction(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Content-Type", "application/text; charset=utf-8");
//The OutputStreamWriter wr passes the string containing encoded parameters to the php file.
OutputStreamWriter wr = new OutputStreamWriter(httpConn.getOutputStream());
/*This is another methods, which hasnt worked...
OutputStream os = new BufferedOutputStream(httpConn.getOutputStream());
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os, "utf-8"));
...and here is another that didnt work...
PrintWriter wr = new PrintWriter(httpConn.getOutputStream(), true);
wr.print(data); */
wr.write(data);
System.out.println(data); //I used this to check that what was being sent to the server was what I expected. (it is)
//Opens a stream to receive the query response.
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
//Read query response.
String line = null;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
//the following if statement gets ignored for some reason, unless I use "==".
if (line.equals("Connected")){
this.progress.setText("It worked!");
}else{
this.progress.setText("Failed");
}
wr.close();
reader.close();
httpConn.disconnect();
return "true";
}
catch (Exception e) {
e.printStackTrace();
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
}
}
My PHP file uses $username = $_POST['username']; to read the parameter.
Sources I have used:
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
HTTPURLConnection - Outputstream POST to php on webserver
How to pass an argument with POST using HttpUrlConnection
https://www.blackbaud.com/files/support/guides/infinitydevguide/content/java/cocreateaconnectionwithurlconnection.htm
https://www.tutorialspoint.com/android/android_php_mysql.htm
Days of Googling
rickdenhaan's comment helped me solve this.
I changed
httpConn.setRequestProperty("Content-Type", "application/text; charset=utf-8");
to
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

Android HTTPUrlConnection SocketTimeoutException/Indefinite Hang?

I'm working on an Android app for a client, and I'm calling their API to get the info for various parts of my app. There is one call that results on SocketTimeoutException if I set a timeout, or infinitely hangs if I don't; however, it works just fine on the web client(React), so it can't be the server.
Code:
package io.voluntu.voluntu;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class SendApproveHours extends AsyncTask<Bundle, Void, String>{
private StringBuilder sb = new StringBuilder();
private String result;
private ApproveHours approveHours;
public SendApproveHours(ApproveHours approveHours){
this.approveHours = approveHours;
}
protected String doInBackground(Bundle... params){
Bundle b = params[0];
String jwt = b.getString("JWT");
System.out.println(jwt);
boolean approve = b.getBoolean("APPROVE");
int[] id = b.getIntArray("ID");
try {
URL url = new URL("http://voluntu.io/api/hour/update");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(2500 /* milliseconds */); //if i don't do this, it will hang indefinitely
httpURLConnection.setReadTimeout(1500 /* milliseconds */);
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Host", "voluntu.io");
httpURLConnection.setRequestProperty("Origin", "http://voluntu.io");
httpURLConnection.setRequestProperty("Referer", "http://voluntu.io/hours/approve");
httpURLConnection.setRequestProperty("Cookie", "sessionJWT=" + jwt);
httpURLConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("approveOrReject", approve);
jsonObject.put("hourIDs", Arrays.toString(id));
System.out.println(jsonObject);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
int HttpResult = httpURLConnection.getResponseCode(); //hangs here
System.out.println("HTTP RESULT: " + HttpResult);
if(HttpResult == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream(), "utf-8"
));
String line;
while((line = in.readLine()) != null){
sb.append(line);
}
in.close();
}
System.out.println("RESPONSE: " + sb.toString());
httpURLConnection.disconnect();
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e){
e.printStackTrace();
}
return sb.toString();
}
protected void onPostExecute(String result){
approveHours.refreshHours();
}
}
It hangs on getting the HTTP response code for some reason. I checked the headers and body and they are identical to what the web version is sending, so I have no idea why it's not working. Also, calling other parts of their API works just fine, and in fact this code is mostly copy pasted from other parts of my app that call the API. Help is appreciated!
I fixed it. Instead of an array, you must use JSONArray, or the array gets wrapped in quotes when it gets put in the JSON object.

The method DataOutputStream(OutputStream) is undefined for the type

I followed a lot of tutorials to make progress with this project. Now I am following a tutorial to create a Google cloud messaging server using JSON and Jackson library.
I somehow got the right Jackson library of all the libraries on the internet. But an error appeared which is the title of this question.
This is that code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.codehaus.jackson.map.ObjectMapper;
public class POST2GCM {
public static void post(String apiKey, Content content){
try{
//1. url
URL url = new URL("https://android.googleapis.com/gcm/send");
//2. open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3. specify POST method
conn.setRequestMethod("POST");
//4.set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
//5. add json data into POST request body
//5.1 use jackson object mapper to convert contnet object into JSON
ObjectMapper mapper = new ObjectMapper();
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
//5.3 copy content "JSON" into
mapper.writeValue(wr, content);
//5.4 send the request
wr.flush();
//5.5
wr.close();
//6. get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL: "+url);
System.out.println("Response Code: "+responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null){
response.append(inputLine);
}
in.close();
//7. print result
System.out.println(response.toString());
}catch(MalformedURLException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}
I don't know how to fix this one, I've looked for answers but there isn't any answer.
your are missing new keyword
//5.2 get connection stream
DataOutputStream wr = DataOutputStream(conn.getOutputStream());
replace with
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

Urban Airship Push code

I've followed the UA tutorials and got my APID , and successfully recieved test push message on my android device.
Now the next thing that I like to do is to target my device using JAVA and send push messaged.
From what I've seen so far the best way to achieve this is using their web API.
However When I'm trying to send a post message I always get the following error :
java.io.IOException: Server returned HTTP response code: 401 for URL: https://go.urbanairship.com/api/push/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.Sender.Sender.main(Sender.java:56)
This is the code that I use :
package com.Sender;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class Sender {
/**
* #param args
*/
public static void main(String[] args) {
try {
String responseString = "";
String outputString = "";
String username = "MWMoRVhmRXOG6IrvhMm-BA";
String password = "ebsJS2iXR5aMJcOKe4rCcA";
MyAuthenticator ma= new MyAuthenticator(username, password);
Authenticator.setDefault(ma);
URL url = new URL("https://go.urbanairship.com/api/push/");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String APID = "23eef280-19c8-40fc-b798-788f50e255a2";
String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\""+APID+"\"]}";
byte[] buffer = new byte[postdata.length()];
buffer = postdata.getBytes("UTF8");
bout.write(buffer);
byte[] b = bout.toByteArray();
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
InputStreamReader isr = new InputStreamReader(
httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
System.out.println(outputString);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Can you help me please ?
HTTP 401 represent Unauthorized access. In your code even though your created Authenticator, you didn't provide it as part of post request header. Here is tutorial on how to set authenticator for a URLConnection.

Categories

Resources