How to make a POST request using retrofit 2?

后端 未结 2 830
离开以前
离开以前 2021-01-17 11:41

I was only able to run the hello world example (GithubService) from the docs.

The problem is when I run my code, I get the following Error, inside of onFail

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 12:30

    You should be aware of how you want to encode the post params. Important is also the @Header annotation in the following. It is used to define the used content type in the HTTP header.

    @Headers("Content-type: application/json")
    @POST("user/savetext")
        public Call changeShortText(@Body MyObjectToSend text);
    

    You have to encode your post params somehow. To use JSON for transmission you should add .addConverterFactory(GsonConverterFactory.create(gson)) into your Retrofit declaration.

    Retrofit restAdapter = new Retrofit.Builder()
                    .baseUrl(RestConstants.BASE_URL)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient)
                    .build();
    

    Another source of your problem could be that the JSON, that's coming from the rest backend seems to be not correct. You should check the json syntax with a validator, e.g. http://jsonlint.com/.

提交回复
热议问题