SOLVED: Post Request (Basic Layout)

May I ask you a (hopefully) simple question. Am I correct that the post request URL should look something like this:

https://api.spark.io/v1/devices/MYCOREID/MYFUNCTION/?access_token=MYACCESSTOKEN&params=MY,PARAMS

Everytime I try it I´ll get a “false” - “Variable not found”

Thank´s in advance!
Cheers c

Hi @clyde,

If you’re opening the url in a browser, it’ll send it as a “GET” request. You’ll need to change the http request method to “POST”, and set the url params in the request body instead of including them in the url. Checkout the call function api method in sparkjs here -

Thanks!
David

HI @Dave

I´ll try it with something like this:

URL url = new URL("https://api.spark.io/v1/devices/MYCOREID");
String param = "/SCL/?access_token=MYACCESSTOKEN&params=MY,PARAM";
HttpsURLConnection postCon = (HttpsURLConnection) url.openConnection();
postCon.setDoOutput(true);
postCon.setRequestMethod("POST");
postCon.setFixedLengthStreamingMode(param.getBytes().length);
postCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

PrintWriter sendPost = new PrintWriter(postCon.getOutputStream());
out.print(param);
out.close();

Results when I catch the error with something like System.out.println(sendPost.checkError()); in “false” without the quotes :wink:

Hi @clyde,

I’m not sure if that’s Java, C#, etc…, but I think you need to move the ?access_token=MYACCESSTOKEN&params=MY,PARAM portion into a payload that’s not a url parameter.

Thanks,
David

@Dave

It´s Java, sorry don´t mentioned it. I tried already a bunch of methods but without a notable result yet.

                try{
                    // vars
                    url = new URL("https://api.spark.io/v1/devices/MYCOREID/SCL/");
                    String param = "-d access_token=MYACCESSTOKEN -d params=x,y";
                    // Debug
                    Log.d(TAG, "url:         " + url);
                    Log.d(TAG, "param:       " + param);

                    // open connection
                    postCon=(HttpsURLConnection)url.openConnection();
                    // Debug
                    Log.d(TAG, "postCon      " + postCon);

                    // manipulate the method
                    postCon.setDoOutput(true);
                    postCon.setRequestMethod("POST");
                    //postCon.setFixedLengthStreamingMode(param.getBytes().length);
                    //postCon.setRequestProperty("Content-Type", "application/json");

                    // send
                    PrintWriter out  = new PrintWriter(postCon.getOutputStream());
                    out.print(param);
                    // Debug
                    Log.d(TAG, "out:        " + out.checkError());

                    // close connection
                    out.close(); 

All I got is a false… maybe some sleep() for myself could be helpful :wink:

Heya @clyde,

I was reading a java https post request example from here ( http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/ ). I modified your original post to something like this that I suspect might work.

after checking it, I think maybe there was only one modification needed, to change this:

String param = "/SCL/?access_token=MYACCESSTOKEN&params=MY,PARAM";

to this

String param = "access_token=MYACCESSTOKEN&params=MY,PARAM";

full example:

URL url = new URL("https://api.spark.io/v1/devices/MYCOREID/FUNCTION_NAME");

// change here
String param = "access_token=MYACCESSTOKEN&params=MY,PARAM";

HttpsURLConnection postCon = (HttpsURLConnection) url.openConnection();
postCon.setDoOutput(true);
postCon.setRequestMethod("POST");
postCon.setFixedLengthStreamingMode(param.getBytes().length);
postCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

PrintWriter sendPost = new PrintWriter(postCon.getOutputStream());
out.print(param);
out.close();

There might be other small things, like the content-type might be fine as application/json instead of a full form submit. If you want, I really recommend testing requests against requestb.in ( http://requestb.in ). They let you get a url where you can see exactly how your http request came through.

I hope that helps! :slight_smile:

Thanks,
David

@Dave:

I currently try it with DHC - REST/HTTP API Client (Chrome extension)

URL HTTPS: api.spark.io/v1/devices/MYCOREID/MYFUNCTION/
METHOD: POST
Headers:
access_token: MYACCESSTOKEN
params: MY,PARAMS

Tried it several times with the access token from the settings page (build.spark.io) and with and without /MYFUNCTION/ everytime I send the post request I receive an “400 Bad request”.

Nope can´t get it to work.
Everytime “400 - Bad request - Access Token not found”

I have reset the access token, I tried using old ones (works with javascript) but no success with posting the request through my Java File nor through DHC Chrome extension? What the …?! What exactly do I miss?

I requested https://api.spark.io/vi/devices/MYCOREID/?access_token:MYACCESSTOKEN

// 20150108141805
// https://api.spark.io/v1/devices/53ff72065075535122081687/?access_token=fd4cee0e0ac706e5c929df005f579d9bf507df18

{
“id”: “MYCOREID”,
“name”: “CrimsonCore”,
“connected”: true,
“variables”: {

},
“functions”: [
“SCL”
],
“cc3000_patch_version”: “1.29”
}

?! It works well with BDubs Javascript where he send the post request through:
$.post( requestURL, { access_token: aToken, params: paramStr });

I am lost :frowning:

Hi @clyde,

I modified my example above, function name should be a part of the url, but not part of the param string, and access_token is a param in this case and not a header, how's that?

Thanks,
David

Oh another questions popping up here:

Why old access tokens still work after I have reset em? When I request:

I got the exact same result as for:

for my understanding the old access token should result in an error. Maybe the exact same as for invalid requests?
Sorry for spamming :slight_smile: but this is a little bit confusing.

Ok works in DHC Client with settings:

HTTPS: api.spark.io/v1/devices/MYCOREID/MYFUNCTION/
Method: POST

Header: Content-Type: application/json

Body:
access_token: (Text) MYACCESSTOKEN
params: (Text) MY,PARAMS

Mkay :slight_smile: now I should be able to translate that to Java :slight_smile: THX mate!

1 Like

Dear Sparksters,

a working example (sorry a little bit messy) but well, it works! Improvements are up to you, this is the basic Android Code for the JSON POST request. Enjoy:

class PostClient extends AsyncTask<String, Void, String> {
    public String doInBackground(String... myparam) {

        // Predefine variables
        String myParam = new String(myparam[0]);
        URL url;

        try {
            // Stuff variables
            url = new URL("https://api.spark.io/v1/devices/MYCOREID/MYFUNCTION/");
            String param = "access_token=MYACCESSTOKEN&params=MY,"+myParam;
            Log.d(TAG, "param:" + param);

            // Open a connection using HttpURLConnection
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

            con.setReadTimeout(7000);
            con.setConnectTimeout(7000);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setInstanceFollowRedirects(false);
            con.setRequestMethod("POST");
            con.setFixedLengthStreamingMode(param.getBytes().length);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // Send
            PrintWriter out = new PrintWriter(con.getOutputStream());
            out.print(param);
            out.close();

            con.connect();

            BufferedReader in = null;
            if (con.getResponseCode() != 200) {
                in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
                Log.d(TAG, "!=200: " + in);
            } else {
                in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                Log.d(TAG, "POST request send successful: " + in);
            };


        } catch (Exception e) {
            Log.d(TAG, "Exception");
            e.printStackTrace();
            return null;
        }
    // Set null and we´e good to go
    return null;
    }
}

Oh btw. don´t use “application/json” as header parameter, because we send the token in the body therefore this needs to be “x-www-form-urlencoded” :smile:. You can use URLEncoder.encode() but you don´t have to. So feel free to tinker around with this!