Fuel: Proper way to post json with Fuel.post

Created on 5 Mar 2017  路  7Comments  路  Source: kittinunf/fuel

I created a list of pair and converted it to a json string.
I have setted up a node server for reading the request body and the result is:

{ '{"first":"text","second":"hello"},{"first":"id","second":"djahduhdiwd"}': '' }

The whole json is interpretated as the key of the object
I'm using Android with vanilla Java

List<Pair> requestParams = new ArrayList<Pair>(2);
requestParams.add( new Pair("text", "hello") );
requestParams.add( new Pair("id", "djahduhdiwd") );

String jsonString = new Gson().toJson(requestParams);

Fuel.post("http://192.168.0.90:9000/article").body(jsonString, Charset.forName("UTF-8")).responseString(new Handler<String>() {
    @Override
    public void failure(Request request, Response response, FuelError error) {}

    @Override
    public void success(Request request, Response response, String data) {
        Log.v("MainActivity", data);
    }
});

Most helpful comment

This is the snippet that I use to do POST.

val json = JSONObject()
json.put("body", "foo")

//synchronous call
val (ignoredRequest, ignoredResponse, result) =
Fuel.post("https://api.github.com/repos/cookpad/global-android/issues/${pair.second}/comments")
        .header("Authorization" to " token ${pair.first}")
        .body(json.toString())
        .responseString()

//do something with result

result.fold({ /*success*/ }, { /*failure*/ })

Can you try out and see whether you can use it like that?

All 7 comments

I used Java HttpUrlConnection instead of the module

This is the snippet that I use to do POST.

val json = JSONObject()
json.put("body", "foo")

//synchronous call
val (ignoredRequest, ignoredResponse, result) =
Fuel.post("https://api.github.com/repos/cookpad/global-android/issues/${pair.second}/comments")
        .header("Authorization" to " token ${pair.first}")
        .body(json.toString())
        .responseString()

//do something with result

result.fold({ /*success*/ }, { /*failure*/ })

Can you try out and see whether you can use it like that?

how to get and print the result then ?

change the last line to

result.fold(success = {
    println(it.toString())
}, failure = {
    println(String(it.errorData))
})

@Ianzelot1989: Thanks, it's working for me :-)

You should pass params in post instead of body
List<Pair<String, String>> requestParams = new ArrayList>(2);
requestParams.add( new Pair("full_name", "hello") );
requestParams.add( new Pair("email", "[email protected]") );

                Fuel.post(apiRegister, requestParams).responseString(new Handler<String>() {
                    @Override
                    public void failure(Request request, Response response, FuelError error) {
                        Log.d("error", error.toString());
                    }

                    @Override
                    public void success(Request request, Response response, String data) {
                        Log.d("data", data);
                    }
                });`

How do I return minPasswordLength?

`fun getPasswordRequirements(context: Context): Int {
var minPasswordLength: Int = 6

    "/auth/password.json".httpGet().responseString { request, response, result ->
        //do something with response
        request.header(mapOf("Content-Type" to "application/json"))
        Log.println(Log.ASSERT, "password_Curl", request.cUrlString())

        when (result) {
            is Result.Failure -> {
                val data = response.data.toString(Charsets.UTF_8)
                Log.println(Log.ASSERT, "Response_Password_Fail", data)

                val jelement = JsonParser().parse(data)
                val jobject = jelement.asJsonObject
                val errorMessage = if (data.contains("Error")) jobject.get("Error").asString else jobject.get("detail").asString


                val alertDialog = AlertDialog.Builder(context).create()
                alertDialog.setTitle("Password Invalid")
                alertDialog.setMessage(errorMessage)
                alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK"
                ) { dialog, which ->
                    dialog.dismiss()
                }
                alertDialog.show()
                //Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
            }
            is Result.Success -> {
                val data = response.data.toString(Charsets.UTF_8)
                Log.println(Log.ASSERT, "Response_Passwd_Succes", data)

                val jelement = JsonParser().parse(data)
                val jobject = jelement.asJsonObject

                // 6 should be replaced with 8
                minPasswordLength = jobject.get("minimal_length").asInt

            }
        }
    }
    return minPasswordLength
}`

right now I get back the initial value of 6 the API return 8.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SleeplessByte picture SleeplessByte  路  3Comments

Xianyang picture Xianyang  路  4Comments

iNoles picture iNoles  路  5Comments

t-ae picture t-ae  路  5Comments

lionlollipop picture lionlollipop  路  3Comments