We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello! I am trying to get the Sentiment API running in processing. I have used the template found here, and after some tinkering I seem to have almost gotten it working (I hope!).
However I am still not able to print the text that I want. I can't find any errors, but the API is not responding. I've put println's throughout the code, and at line 63:
InputStream in = conn.getInputStream();
it seems to malfunction, as I can read the println '7', but not '8' which is immediately after that line.
Testing on mashape leads me to believe the API works otherwise, so I think it is due to some error of my own.
Here is the code:
import java.io.*;
import java.net.*;
import java.net.HttpURLConnection;
import java.net.URL;
StringBuilder response = new StringBuilder();
JSONObject ezm;
//HttpURLConnection conn;
void setup() {
size(300,300);
ezm = new JSONObject();
ezm.setString("txt", "Happy days");
URL url = null;
println(1);
try
{
url = new URL("http://sentiment.vivekn.com/api/text/");
println(2);
}
catch (MalformedURLException ex)
{
println("Url fejler");
}
if(url == null)
{
println("url øv");
}
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
println(3);
try {
conn.setRequestMethod("POST"); //use post method
conn.setDoOutput(true); //we will send stuff
conn.setDoInput(true); //we want feedback
conn.setUseCaches(false); //no caches
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("Content-Type","application/json");
println(4);
}
catch (ProtocolException e) {
println("æv");
}
OutputStream out = conn.getOutputStream();
try {
OutputStreamWriter wr = new OutputStreamWriter(out);
wr.write(ezm.toString()); //ezm is my JSON object containing the api commands
wr.flush();
wr.close();
println(5);
}
finally { //in this case, we are ensured to close the output stream
if (out != null)
out.close();
println(6);
}
println(7);
InputStream in = conn.getInputStream();
println(8);
BufferedReader rd = null;
try {
rd = new BufferedReader(new InputStreamReader(in));
String responseSingle = null;
while ((responseSingle = rd.readLine()) != null) {
response.append(responseSingle);
}
println("The server response is " + response);
}
catch (IOException e) {
println("hm");
}
finally { //in this case, we are ensured to close the input stream
if (in != null)
in.close();
}
}
catch (IOException e) {
}
finally { //in this case, we are ensured to close the connection itself
}
}
Hope someone can spot the errors! Thank you
F
Edit: The code tag seems to have put html around the link in my code. Please ignore that
Answers
Simon Brix is a wizard. Here is the functional code, with some obsolete parts: