Retrofit2 post method showing server internal erro

2019-05-13 23:24发布

问题:

I am very new to retroft. I am using retrofit2 for my API integration. I have an API for POST method. I am sending the body from postman and I am getting response, but when I am doing this programatically I am getting "Internal Server Error".

This is my post man response

And my code is

 private void savePost(String post_body, String permission, String latitude, String longitude, String location) {

        try {

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BuildConfig.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            ApiService api = retrofit.create(ApiService.class);


            /**
             * Calling JSON
             */


        Log.d("TOKEN","JWT "+sharedPrefs.getPref(sharedPrefs.token));
            Call<PostModel> call = api.postData("JWT "+sharedPrefs.getPref(sharedPrefs.token), post_body, permission, latitude, longitude, location);

           /* "JWT "+sharedPrefs.getPref(sharedPrefs.token)
*/
            /**
             * Enqueue Callback will be call when get response...
             */
            call.enqueue(new Callback<PostModel>() {
                @Override
                public void onResponse(Call<PostModel> call, Response<PostModel> response) {


                    Log.d(" write post CODE", response.raw() + "");

                    if (response.isSuccessful()) {


                        Log.e("post sucess..", "post sucess..");

                        Toast.makeText(ActivityWritePost.this,"Successfully Posted",Toast.LENGTH_SHORT).show();


                    } else {


                    }
                }

                @Override
                public void onFailure(Call<PostModel> call, Throwable t) {
                    //Dismiss Dialog


                    Log.d("POST_API", t.getCause() + "");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

And my model class is

public class PostModel {

        @SerializedName("status")
        @Expose
        private Integer status;
        @SerializedName("message")
        @Expose
        private String message;
        @SerializedName("data")
        @Expose
        private Data data;

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public Data getData() {
            return data;
        }

        public void setData(Data data) {
            this.data = data;
        }

    public class Data {

        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("user")
        @Expose
        private Integer user;
        @SerializedName("post_image")
        @Expose
        private Object postImage;
        @SerializedName("post_body")
        @Expose
        private String postBody;
        @SerializedName("permission")
        @Expose
        private String permission;
        @SerializedName("location")
        @Expose
        private String location;
        @SerializedName("latitude")
        @Expose
        private Integer latitude;
        @SerializedName("longitude")
        @Expose
        private Integer longitude;
        @SerializedName("created")
        @Expose
        private String created;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getUser() {
            return user;
        }

        public void setUser(Integer user) {
            this.user = user;
        }

        public Object getPostImage() {
            return postImage;
        }

        public void setPostImage(Object postImage) {
            this.postImage = postImage;
        }

        public String getPostBody() {
            return postBody;
        }

        public void setPostBody(String postBody) {
            this.postBody = postBody;
        }

        public String getPermission() {
            return permission;
        }

        public void setPermission(String permission) {
            this.permission = permission;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public Integer getLatitude() {
            return latitude;
        }

        public void setLatitude(Integer latitude) {
            this.latitude = latitude;
        }

        public Integer getLongitude() {
            return longitude;
        }

        public void setLongitude(Integer longitude) {
            this.longitude = longitude;
        }

        public String getCreated() {
            return created;
        }

        public void setCreated(String created) {
            this.created = created;
        }

    }

}

And this is my interface

 @FormUrlEncoded
    @POST(BuildConfig.POSTSTATUS)
    Call<PostModel> postData(@Header("Authorization") String Authorization, @Field("post_body") String post_body, @Field("permission") String permission, @Field("latitude") String latitude, @Field("longitude") String longitude, @Field("location") String location);

I tried my interface with Multipart also, even though same internal server error.

Please help me out of this.

Thanks in advance.

回答1:

It's because of a small issue in post method Retrofit 2 called content-type. You just need to give the content type as form-data for header and then access it. Also, you need to make one POJO class and pass the values in your retrofit method via that newly made POJO class using the annotation as @Body.

Here is the demonstration of it:

In your interface, declare this(Here you give the content-type as form-data because the backend you are accessing, is accepting the content-type as form-data)

Ex:

@Headers("Content-Type: form-data")
@POST(BuildConfig.POSTSTATUS)
Call<ApiModel> postData(@Header("Authorization") String Authorization, @Body WriteAPostModel writeAPostModel);

Now here is the WriteAPostModel class which is your POJO class:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by Adhish on 02/02/17.
 */

public class WriteAPostModel {

    @SerializedName("post_body")
    @Expose
    private String post_body;

    @SerializedName("permission")
    @Expose
    private String permission;

    @SerializedName("latitude")
    @Expose
    private String latitude;


    @SerializedName("longitude")
    @Expose
    private String longitude;



    @SerializedName("location")
    @Expose
    private String location;


    public String getPost_image() {
        return post_image;
    }

    public void setPost_image(String post_image) {
        this.post_image = post_image;
    }

    @SerializedName("post_image")
    @Expose

    private String post_image;



    public String getPost_body() {
        return post_body;
    }

    public void setPost_body(String post_body) {
        this.post_body = post_body;
    }


    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getPermission() {
        return permission;
    }

    public void setPermission(String permission) {
        this.permission = permission;
    }

}

Finally, consume these in your activity like shown below:

private void savePost(String post_body,String post_image, String permission, String latitude, String longitude, String location) {

    try {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiService api = retrofit.create(ApiService.class);

        WriteAPostModel writeAPostModel = new WriteAPostModel();
        writeAPostModel.setPost_body(post_body);
        writeAPostModel.setPermission(permission);
        writeAPostModel.setLatitude(latitude);
        writeAPostModel.setLongitude(longitude);
        writeAPostModel.setLocation(location);
        writeAPostModel.setPost_image(post_image);

        Call<ApiModel> call = api.postData("JWT "+sharedPrefs.getPref(sharedPrefs.token), writeAPostModel);

        /**
         * Enqueue Callback will be call when get response...
         */
        call.enqueue(new Callback<ApiModel>() {
            @Override
            public void onResponse(Call<ApiModel> call, Response<ApiModel> response) {


                Log.d(" write post CODE", response.raw() + "");

                if (response.isSuccessful()) {



                    Toast.makeText(ActivityWritePost.this,"Successfully Posted",Toast.LENGTH_SHORT).show();

                    finish();


                } else {


                }
            }

            @Override
            public void onFailure(Call<ApiModel> call, Throwable t) {
                //Dismiss Dialog


                Log.d("POST_API", t.getCause() + "");
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Where ApiModel is your POJO class to get the responses.



回答2:

It is bit difficult to tell without actually debugging the url.But usual reasons could be as follows, which I encountered. 1) The base url and the url in post method have to be differentiated properly.

2) If those parameters are parameters for url, then try to send them as a body for eg

 public Call <String> getLoginCred(@Body HashMap<String,Object> userM);

if the parameters are parameters to the url then simply make an url string call with @url.

Check if the BuildConfig.POSTSTATUS string is proper, ie your base url should be something like https:/192.168.1.1/ and Poststatus string is like "/api/User/AuthanticateUserById" so the / is not missing and some other url is not mixed with it.



回答3:

use get method
 @FormUrlEncoded
    @GET(BuildConfig.POSTSTATUS)

url=t/api/mobile/user/pos url uses GET