2

I have an app running on J2ME that needs to access the Instagram API. Specifically, I need to post a comment. This is a Post method. So I try to add the "text" parameter to the body of the request by using HttpConnection.setRequestProperty(), but this doesn't seem to work, as Instagram doesn't recognize that the parameter is present. I think this method is failing to write the parameter to the body of the Http request. Any idea how I can make this work in j2me?

Here's my code:

    InputStream is = null;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    byte[] response = null;
    HttpConnection connection = null;

    String url = "";
    try {
      url = "https://api.instagram.com/v1/media/" + mediaId + "/comments?access_token="+InstagramAPIUtil.accessTokenTest;// POST
      url = Util.urlEncodeSpaces(url);


        System.out.println(url);
        connection = (HttpConnection)Connector.open(url,Connector.READ_WRITE);

        connection.setRequestMethod(HttpConnection.POST);

        connection.setRequestProperty("text", comment);

        if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
            is = connection.openInputStream();

            if (is != null) {
                int ch = -1;

                while ((ch = is.read()) != -1) {
                    bos.write(ch);
                }

                response = bos.toByteArray();
            }
            System.out.println("response: "+new String(response));
            System.out.println("request: "+connection.getRequestProperty("text"));
            return true;
        }

And here's what I'm getting back from Instagram:

{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"Missing 'text'"}}
James Harpe
  • 4,315
  • 8
  • 47
  • 74

1 Answers1

2

I have not much experience in the HTTP area, but I think you need to write to the output stream that you can get from connection. I don't see where in your code you send actual data.

  HttpURLConnection c = (HttpURLConnection) new URL("").openConnection();
  OutputStream out = c.getOutputStream();
  InputStream in = c.getInputStream();
mike
  • 4,929
  • 4
  • 40
  • 80
  • See the documentation here: http://docs.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/javax/microedition/io/HttpConnection.html. It switches to the connected state when I call connection.getResponseCode(). – James Harpe Sep 02 '13 at 23:06
  • In the link you provided, you should read the paragraph 'Example using POST with HttpConnection'. I still don't see where your output stream is coming from. – mike Sep 02 '13 at 23:12
  • Oh, I see what you're saying now. Thanks so much, this is what I need! – James Harpe Sep 03 '13 at 01:04