Http Post a JSON Object to API [Solved]

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

  • Answer ✓

    Simon Brix is a wizard. Here is the functional code, with some obsolete parts:

    import java.io.*;
    import java.net.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    StringBuilder response = new StringBuilder();
    JSONObject ezm;
    HttpURLConnection conn = null;
    
    static class Util {
    public static String streamToString(InputStream is) throws IOException {
            StringBuilder sb = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        }
    }
    
    void setup() {
    
      size(300,300);
      ezm = new JSONObject();
      ezm.setString("txt", "I am sad");
    
      URL url = null;
    try
    {
    url = new URL("http://sentiment.vivekn.com/api/text/");
    }
    catch (MalformedURLException ex)
    {
    println("Url fejler");
    }
    if(url == null)
    {
    print("url øv");
    }
    
      try {
        conn = (HttpURLConnection) url.openConnection();
        try {
          conn.setRequestMethod("POST"); //use post method
          conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          conn.setRequestProperty("Accept", "application/json");
          conn.setDoOutput(true); //we will send stuff
          //conn.setDoInput(true); //we want feedback
          //conn.setUseCaches(false); //no caches
          //conn.setAllowUserInteraction(false);
          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write("txt=Very bad"); //ezm is my JSON object containing the api commands
          wr.flush();
          wr.close();
          print("Test2");
          print("Test1");
          /*int responseCode = conn.getResponseCode();
        String responseMessage = conn.getResponseMessage();
    
        InputStream is = null;
        if (responseCode >= 400) {
          is = conn.getErrorStream();
        } else {
          is = conn.getInputStream();
        }
    
    
        String resp = responseCode + "\n" + responseMessage + "\n>" + Util.streamToString(is) + "<\n";
    
        print(resp);*/
        } 
        catch (ProtocolException e) {
          println("æv");
        }
    
        print("Test3");
    
    // Open a stream which can read the server response*********************************
        print("Test4");
    
        InputStream in = conn.getInputStream();
        print("Test5");
        BufferedReader rd = null;
        print("Test6");
        try {
          print("Test7");
          rd = new BufferedReader(new InputStreamReader(in));
          String responseSingle = null;
          print("Test8");
          while ((responseSingle = rd.readLine()) != null) {
            response.append(responseSingle);
            print("Test9");
          }
          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 
    
     }
    }
    
Sign In or Register to comment.