I have a problem with gae. I have an application http://www.similarityface.appspot.com/query. I am trying through a program in java to communicate with this application to perform query, via the POST method. The problem that is generating 500 error.
The code is below, could someone help me telling what I'm doing wrong.
public class Vetores_Facebook {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
final String server = "https://www.similarityface.appspot.com/query";
URL url = null;
try {
url = new URL(server);
} catch (MalformedURLException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
HttpURLConnection urlConn = null;
try {
// URL connection channel.
urlConn = (HttpURLConnection) url.openConnection();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
try {
urlConn.setRequestMethod("POST");
} catch (ProtocolException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ok");
}
else{
int x = urlConn.getResponseCode();
System.out.println("error "+x);
}
}
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
The problem is you are calling urlConn.connect(); which seems to flush any output buffers you may have and prepares the connection to get an input stream. Trying to write to open an output stream after this will cause an exception.
Use the example given here for the correct way to do this: https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet#Using_HttpURLConnection
Related
I'm trying to access TheRockTrading Exchange APIs, but when i try to access the private balance query, gives FileNotFoundException
public static void main(String[] args) throws InterruptedException {
try {
//MANNAGGIA ALLA MADONNA
URL a = null;
try {
a = new URL("https://api.therocktrading.com/v1/balance");
} catch (MalformedURLException ex) {
Logger.getLogger(Miner.class.getName()).log(Level.SEVERE, null, ex);
}
HttpsURLConnection ac = (HttpsURLConnection) a.openConnection();
ac.setRequestMethod("GET");
ac.setDoInput(true);
ac.setAllowUserInteraction(false);
ac.setRequestProperty("User-Agent", "infofetch");
ac.setRequestProperty("Connection", "close");
try(BufferedReader br = new BufferedReader(new InputStreamReader(ac.getInputStream()))) {
String l = null;
while ((l=br.readLine())!=null) {
System.out.println(l);
}
} catch(IOException ioex) {
System.err.println("IOException while reading");
ioex.printStackTrace();
}
} catch (IOException ex) {
Logger.getLogger(Miner.class.getName()).log(Level.SEVERE, null, ex);
}
}
APIkey and signature are missing but i should at least receive something instead of FileNotFoundException
java.io.FileNotFoundException: https://api.therocktrading.com/v1/balance
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at Miner.main(Miner.java:37)
I was able to do this with the Socket class. However I wanted to get something along the lines of what HttpUrlConnection has to offer.
Right now I am doing the following:
public void checkServerStatus(String IP_ADDRESS, int PORT, String SERVER_NAME) {
try(Socket s = new Socket(IP_ADDRESS, PORT)) {
System.out.println("Connection good on "+SERVER_NAME);
} catch (IOException ex) {
System.out.println("There was an IO error "+ ex);
}catch(SecurityException ex) {
System.out.println("There was an security error "+ ex);
} catch (IllegalArgumentException ex){
System.out.println("There was an IllegalArgumentException "+ ex);
}
}
However I would like do something like:
public static String getStatus(String url) throws IOException {
String result = "";
try {
URL siteURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == 200) {
result = "Green";
}
} catch (Exception e) {
result = "->Red<-";
}
return result;
}
However with only the IP address and the Port I want to check.
After reading the URL API I cannot do that and HttpUrlConnection is dependent on URL.
I am trying to create a server health status type of program, and if there is a problem it returns a code.
I will like the ControlFx MaskerPane to be showing while the request is going on. I have this code on a button action to make the network request.
if(mp==null){
mp=new MaskerPane();
stackPane.getChildren().add(mp);
mp.setVisible(false);
}
try {
mp.setVisible(true);
JSONObject verifyKey = new Network().verifyKey(pinF.getText(), phoneF.getText(), mp);
if (verifyKey != null) {
String string = verifyKey.getString("ans");
mp.setVisible(false);
if (string.equals("1")) {
// Thanks for buying
} else {
error.setText("Key already used");
error.setVisible(true);
}
}
} catch (JSONException ex) {
mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
}
However the verify method in my Network class looks like
public JSONObject verifyKey(String key, String phone, MaskerPane mp){
this.mp=mp;
String url = "http://theUrl";
String httpcall = httpcall(url, "func","verify","key",key,"phone",phone,"type","eDesk");
try {
return new JSONObject(httpcall);
} catch (JSONException ex) {
Logger.getLogger(Network.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public String httpcall(String url,String ...args) {
try {
// String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String formatin = "";
Object values[] = new String[args.length/2];
int valCount =0;
for (int i = 0; i < args.length; i+=2) {
formatin+=args[i]+"=%s&";
values[valCount]=URLEncoder.encode(args[i+1], charset);
valCount++;
}
String query = String.format(formatin,values);
query=query.substring(0, query.length()-1);
//Remember to remove proxy lines before production
//SocketAddress addr = new InetSocketAddress("127.0.0.1", 8080);
//Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
URLConnection connection = new URL(url).openConnection(proxy);
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
//return getStringFromInputStream(response);
} catch (UnsupportedEncodingException ex) {
if(mp!=null)mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
}catch (MalformedURLException ex) {
if(mp!=null)mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
//if(mp!=null)mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
//return "{\"ans\":\"1\"}";//xpectd on success
//return "{\"ans\":\"0\",\"err\":\"1\"}";//xpectd on failure
}
return null;
}
The problem is the maskerpane wont show until the network request is called is complete.
I found out I need to execute the network operation in another thread. One can use Executor services. These can be found in javafx concurrency package
if (mp == null) {
mp = new MaskerPane();
stackPane.getChildren().add(mp);
mp.setVisible(false);
}
mp.setVisible(true);
Runnable task = () -> {
try {
JSONObject verifyKey = new Network().verifyKey(pinF.getText(), phoneF.getText(), mp);
if (verifyKey != null) {
String string = verifyKey.getString("ans");
//Updating ui from another thread need you to use Platform.runLatter... So wrapping the below with runLatter to avoid exceptions
mp.setVisible(false);
if (string.equals("1")) {
// Thanks for buying
} else {
error.setText("Key already used");
error.setVisible(true);
}
}
Thread back = new Thread(task);
back.setPriority(Thread.MAX_PRIORITY);
back.setDaemon(true);
back.start();
} catch (JSONException ex) {
mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Run the task in a background thread
Thread back = new Thread(task);
back.setPriority(Thread.MAX_PRIORITY);
back.setDaemon(true);
back.start();
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
Here is the code I am trying to send SMS through the red Oxygen server
Here is the code I am executing below
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
DataOutputStream output = null;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeBytes(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
While executing I am getting the below exception :
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
at com.nextenders.server.LoginServlet.SendSMS(LoginServlet.java:143)
I tried with increasing connection timeout and turn off the firewall ...etc but no luck .Can anyone help me to trace the problem ??
Here is the tutorial I'm following :
http://www.redoxygen.com/developers/java/
The "*"s in my code is credentials for the gateway .
This is a network topology problem. You can't connect to that site from where you are. Some intervening firewall, probably your own, is preventing it. Talk to your netadmin.
The following code runs fine when I have tested it with other websites (as I don't have access your the messaging API):
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
try {
connection.connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
final DataOutputStream output;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeUTF(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
final InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(connection.getErrorStream(), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println("Error response code from server. Error was:");
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
throw new RuntimeException(e);
}
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
It will toString the various streams and has error handling when the stream doesn't connect.
The most important change is using the DataOutputStream.writeUTF method rather than just the write method - this will ensure than the POST data is encoded correctly. I don't think this is your issue as the problem is on connect.
The example code you used seems to be unaware of Java naming conventions or best practices to I have tidied it considerably.
The stream reader can be pulled out and into a separate method to avoid duplication.
I would recommend pointing it at another website (I used my work's) and seeing if you get output.
I have two methods, one that serialize the Object, and it works ok:
public void record()throws RecordingException
{
ObjectOutputStream outputStream = null;
try
{
outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
outputStream.writeObject(this);
} catch (FileNotFoundException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
} catch (IOException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
}finally
{
try
{
if (outputStream != null) outputStream.close();
} catch (IOException ex){}
}
}
The problem here when deserializing the object, I get EOFException!:
public final User loadObject(UserType usertype) throws InvalidLoadObjectException
{
ObjectInputStream istream = null;
String path = null;
if (usertype == UserType.EMPLOYEE)
{
path = "data/employee.dat";
}else if (usertype == UserType.CUSTOMER)
{
path = "data/customer.dat";
}else
throw new InvalidLoadObjectException("Object is not a sub class of User");
try
{
istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));
User u = loadObject(istream);
istream.close();
return u;
}catch (EOFException ex)
{
System.out.println(ex.getMessage());
return null;
}catch(Exception ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
{
try
{
return (User) stream.readObject();
} catch (IOException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
} catch (ClassNotFoundException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
I don't know if this is the cause of your problem, but the code that writes the file has a subtle flaw. In the finally block, you close the stream and ignore any exceptions. If the close() method performs a final flush(), then any exceptions thrown in the flush will go unreported.
Try outputStream.flush() before closing your stream in serialization object.
The file was empty, or didn't contain the full serialization of the object.