Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit 2.0 POST method with body is String

This question may have been asked before but with new version 2.0 I did not find any correct answer yet.

My problem as below:

public interface  AuthenticationAPI {

    @POST("token")
    Call<String> authenticate(@Body String  body);

}

Then I call:

Retrofit retrofit = new Retrofit.Builder().baseUrl(authenUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AuthenticationAPI authen = retrofit.create(AuthenticationAPI.class);


        try {
            Call<String> call1 = authen.authenticate(authenBody);
            call1.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Response<String> response, Retrofit retrofit) {
                    Log.d("THAIPD", "Success " + response.raw().message());
                }

                @Override
                public void onFailure(Throwable t) {
                    Log.e("THAIPD", " FAIL " + t.getMessage());
                }
            });
        } catch (Exception e) {
            Log.e("THAIPD", e.getMessage());
            e.printStackTrace();
        }

Then I receive the response as protocol=http/1.1, code=400, message=Bad Request, That means my body parameter was not correct.

When I try to make a request by other tool as Postman I get the correct result with code is 200.

I found this answer but with Retrofit 2.0 I can not find TypedString class.

Here is the result when I try by another tool (DHC) enter image description here

like image 771
ThaiPD Avatar asked Oct 15 '15 04:10

ThaiPD


1 Answers

UPDATE:
Retrofit2.0 has now own converter-scalars module for String and primitives (and their boxed).

com.squareup.retrofit2:converter-scalars

You can write custom Converter and Retrofit repository has a own String Converter implementation sample: ToStringConverterFactory

class ToStringConverterFactory extends Converter.Factory {
  private static final MediaType MEDIA_TYPE = MediaType.parse("text/plain");

  @Override
  public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
      return new Converter<ResponseBody, String>() {
        @Override public String convert(ResponseBody value) throws IOException {
          return value.string();
        }
      };
    }
    return null;
  }

  @Override public Converter<?, RequestBody> toRequestBody(Type type, Annotation[] annotations) {
    if (String.class.equals(type)) {
      return new Converter<String, RequestBody>() {
        @Override public RequestBody convert(String value) throws IOException {
          return RequestBody.create(MEDIA_TYPE, value);
        }
      };
    }
    return null;
  }
}

and related issue are tracked here.

like image 175
ytRino Avatar answered Oct 15 '22 01:10

ytRino