calvert
calvert

Reputation: 721

Cannot read String response of Retrofit and RxJava POST request

Api Interface

@FormUrlEncoded
@POST("register.php")
Observable<String> registerUser(@Field("email") String email, @Field("password") String password);

In my MVP presenter

onCreate{
  Observable<String> registerUserObservable= 
  apiInterface.registerUser("[email protected]", "1234");
  registerUserObservable.subscribeOn("schedulers.io())
         .observeOn(AndroidSchedulers.mainThread())
         .subscribe(this::handleResult, this::handleError);
}

//methods
private void handleResult(String response){
  Log.d(TAG, response);
}

private void handleError(Throwable throwable){
  Log.d(TAG, throwable.getMessage());
}

These are my code for retrofit and rxjava and I am suppose to post an email and password to register a user. The server should return a string on success and a string on failure too.

Gson gson = new GsonBuilder()
           .setLenient()
           .create();

retrofit = new retrofit2.Retrofit.Builder()
           .baseUrl(BASE_URL)
           .addConverterFactory(GsonConverterFactory.create(gson))
           .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
           .build();

I added the gson setLenient code portion because it gives me Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 1 path $ error if I don't have it. After adding this, I am getting JSON document was not fully consumed. error which I do not know how to solve it. Is this because of the return response from the server is a string?

Thanks in advance.

Upvotes: 0

Views: 775

Answers (1)

ytRino
ytRino

Reputation: 1459

If your server sends normal string response not JSON string, you need to use another converter that reads string into String. Happily there is Scalars converter officially.

A Converter which supports converting strings and both primitives and their boxed types to text/plain bodies.

Upvotes: 1

Related Questions