How to POST raw whole JSON in the body of a Retrofit request?

前端 未结 23 2739
面向向阳花
面向向阳花 2020-11-22 00:57

This question may have been asked before but no it was not definitively answered. How exactly does one post raw whole JSON inside the body of a Retrofit request?

See

23条回答
  •  野性不改
    2020-11-22 01:47

    1)Add dependencies-

     compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    

    2) make Api Handler class

        public class ApiHandler {
    
    
      public static final String BASE_URL = "URL";  
    
        private static Webservices apiService;
    
        public static Webservices getApiService() {
    
            if (apiService == null) {
    
               Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();
                Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(gson)).baseUrl(BASE_URL).build();
    
                apiService = retrofit.create(Webservices.class);
                return apiService;
            } else {
                return apiService;
            }
        }
    
    
    }
    

    3)make bean classes from Json schema 2 pojo

    Remember
    -Target language : Java -Source type : JSON -Annotation style : Gson -select Include getters and setters -also you may select Allow additional properties

    http://www.jsonschema2pojo.org/

    4)make interface fro api calling

        public interface Webservices {
    
    @POST("ApiUrlpath")
        Call ApiName(@Body JsonObject jsonBody);
    
    }
    

    if you have a form-data parameters then add below line

    @Headers("Content-Type: application/x-www-form-urlencoded")
    

    Other way for form-data parameter check this link

    5)make JsonObject for passing in to body as parameter

     private JsonObject ApiJsonMap() {
    
        JsonObject gsonObject = new JsonObject();
        try {
            JSONObject jsonObj_ = new JSONObject();
            jsonObj_.put("key", "value");
            jsonObj_.put("key", "value");
            jsonObj_.put("key", "value");
    
    
            JsonParser jsonParser = new JsonParser();
            gsonObject = (JsonObject) jsonParser.parse(jsonObj_.toString());
    
            //print parameter
            Log.e("MY gson.JSON:  ", "AS PARAMETER  " + gsonObject);
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
        return gsonObject;
    }
    

    6) Call Api Like this

    private void ApiCallMethod() {
        try {
            if (CommonUtils.isConnectingToInternet(MyActivity.this)) {
                final ProgressDialog dialog;
                dialog = new ProgressDialog(MyActivity.this);
                dialog.setMessage("Loading...");
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
    
                Call registerCall = ApiHandler.getApiService().ApiName(ApiJsonMap());
                registerCall.enqueue(new retrofit2.Callback() {
                    @Override
                    public void onResponse(Call registerCall, retrofit2.Response response) {
    
                        try {
                            //print respone
                            Log.e(" Full json gson => ", new Gson().toJson(response));
                            JSONObject jsonObj = new JSONObject(new Gson().toJson(response).toString());
                            Log.e(" responce => ", jsonObj.getJSONObject("body").toString());
    
                            if (response.isSuccessful()) {
    
                                dialog.dismiss();
                                int success = response.body().getSuccess();
                                if (success == 1) {
    
    
    
                                } else if (success == 0) {
    
    
    
                                }  
                            } else {
                                dialog.dismiss();
    
    
                            }
    
    
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                Log.e("Tag", "error=" + e.toString());
    
                                dialog.dismiss();
                            } catch (Resources.NotFoundException e1) {
                                e1.printStackTrace();
                            }
    
                        }
                    }
    
                    @Override
                    public void onFailure(Call call, Throwable t) {
                        try {
                            Log.e("Tag", "error" + t.toString());
    
                            dialog.dismiss();
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                    }
    
                });
    
            } else {
                Log.e("Tag", "error= Alert no internet");
    
    
            }
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题