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

前端 未结 23 2347
面向向阳花
面向向阳花 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:56

    In Retrofit2, When you want to send your parameters in raw you must use Scalars.

    first add this in your gradle:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
    

    Your Interface

    public interface ApiInterface {
    
        String URL_BASE = "http://10.157.102.22/rest/";
    
        @Headers("Content-Type: application/json")
        @POST("login")
        Call getUser(@Body String body);
    
    }
    

    Activity

       public class SampleActivity extends AppCompatActivity implements Callback {
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_sample);
    
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(ApiInterface.URL_BASE)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
    
            ApiInterface apiInterface = retrofit.create(ApiInterface.class);
    
    
            // prepare call in Retrofit 2.0
            try {
                JSONObject paramObject = new JSONObject();
                paramObject.put("email", "sample@gmail.com");
                paramObject.put("pass", "4384984938943");
    
                Call userCall = apiInterface.getUser(paramObject.toString());
                userCall.enqueue(this);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
    
        @Override
        public void onResponse(Call call, Response response) {
        }
    
        @Override
        public void onFailure(Call call, Throwable t) {
        }
    }
    

提交回复
热议问题