Ahmet Yılmaz
Ahmet Yılmaz

Reputation: 67

How can I post message in Retrofit2?

This project run with a web server. When user click button, it should post the message inside of EditText. I use Retrofit2 for it. The program has stoped when I click button.

ApiInterface.java

@POST("api/EmergencyNotification/SendNotification")
Call<SendMessageModel>postMessage(@Header("Authorization") String token,
                              //  @Field(("PhotoRequest")) String photoRequest,
                              //  @Field(("Location")) String location,
                                @Field(("MessageBody")) String messageBody);
                                //  @Field(("AnswerValue")) String answerValue);   

In the button OnClick this function runs:

protected void postMessage(){
    startProgress();
    String authorization = SessionHelper.getCustomerTokenWithBearer();
   // Loc = lattitude + longitude;
    Call<SendMessageModel> call = ApiService.apiInterface.postMessage(authorization,
            mesaj.getText().toString().trim());

   call.enqueue(new Callback<SendMessageModel>() {
        @Override
        public void onResponse(Call<SendMessageModel> call, Response<SendMessageModel> response) {
            stopProgress();

            if (response.isSuccessful()){

                if (response.body() != null){
                    DialogHelper.showDialogWithOneButton("",response.body().getData());
               }
            }
            else {
                ApiErrorUtils.parseError(response);
            }
        }

        @Override
        public void onFailure(Call<SendMessageModel> call, Throwable t) {

            stopProgress();
            DialogHelper.showFailedDialog();
        }
    });
}

Upvotes: 0

Views: 62

Answers (2)

Ahmet Yılmaz
Ahmet Yılmaz

Reputation: 67

Ok. I solved it now. My api url was wrong and I added new @Multipart and @Part instead of @Field.

@POST("api/EmergencyNotification/SendMessage")
  Call<SendMessageModel>postMessage(@Header("Authorization") String token,

                                    @Part(("MessageBody")) String messageBody);

Upvotes: 1

Samuel Eminet
Samuel Eminet

Reputation: 4737

You are missing @FormUrlEncoded attribute since you are using field attribute instead of body

@POST("api/EmergencyNotification/SendNotification")
@FormUrlEncoded
Call<SendMessageModel>postMessage(@Header("Authorization") String token,
...

Upvotes: 0

Related Questions