Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit: Sending POST request to server in android

I am using Retrofit to call APIs. I am sending a post request to API but in the callback I am getting empty JSON like this {}.

Below is the code for RetrofitService

@POST("/com/searchusers.php")
void getUser(@Body JSONObject searchstring, Callback<JSONObject> callBack);

where searchstring JSON is like this {"search":"nitesh"}. In response I am supposed to get the detail of user "nitesh".

Below is the code for sending POST request

RetrofitService mRetrofitService = app.getRetrofitService();
    mRetrofitService.getUser(user, new Callback<JSONObject>() {

        @Override
        public void success(JSONObject result, Response arg1) {
            System.out.println("success, result: " + result);
        }

        @Override
        public void failure(RetrofitError error) {
            System.out.println("failure, error: " + error);
        }
    });

I am getting this output success, result: {}

Expected output is success, result: {"name":"nitesh",....rest of the details}

Edit: I tried using Response instead of JSONObject like this CallBack<Response> and then I converted the raw response into String and I got the expected result. But the problem is its in String, I want the response in JSONObject.

How can I get the exact result using CallBack<JSONObject> ...?

like image 323
Nitesh Kumar Avatar asked May 25 '14 08:05

Nitesh Kumar


People also ask

What is retrofitting in Android?

Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services.

What is retrofit in Android with example?

In Android, Retrofit is a REST Client for Java and Android by Square inc under Apache 2.0 license. Its a simple network library that used for network transactions. By using this library we can seamlessly capture JSON response from web service/web API.

How do you post raw whole JSON in the body of a retrofit request?

REST APIs provide us a functionality with the help of which we can add data to our database using REST API. For posting this data to our database we have to use the Post method of REST API to post our data. We can post data to our API in different formats.


1 Answers

After waiting for the best response I thought of answering my own question. This is how I resolved my problem.

I changed the converter of RestAdapter of RetrofitService and created my own Converter. Below is my StringConverter

static class StringConverter implements Converter {

    @Override
    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
        String text = null;
        try {
            text = fromStream(typedInput.in());
        } catch (IOException ignored) {/*NOP*/ }

        return text;
    }

    @Override
    public TypedOutput toBody(Object o) {
        return null;
    }

    public static String fromStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);
        }
        return out.toString();
    }
}

Then I set this converter to the RestAdapter in the Application class.

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(BASE_URL)
        .setConverter(new StringConverter())
        .build();
    mRetrofitService = restAdapter.create(RetrofitService.class);

Now whenever I use Retrofit, I get the response in String. Then I converted that String JSONObject.

RetrofitService mRetrofitService = app.getRetrofitService();
mRetrofitService.getUser(user, new Callback<String>() {

    @Override
    public void success(String result, Response arg1) {
        System.out.println("success, result: " + result);
        JSONObject jsonObject = new JSONObject(result);
    }

    @Override
    public void failure(RetrofitError error) {
        System.out.println("failure, error: " + error);
    }
});

Hence, I got the result in JSON form. Then I parsed this JSON as required.

like image 199
Nitesh Kumar Avatar answered Oct 26 '22 18:10

Nitesh Kumar