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

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

    I wanted to compare speed of volley and retrofit for sending and receiving data I wrote below code (for retrofit part)

    first dependency:

    dependencies {
         implementation 'com.squareup.retrofit2:retrofit:2.4.0'
         implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
    }
    

    Then interface:

     public interface IHttpRequest {
    
        String BaseUrl="https://example.com/api/";
    
        @POST("NewContract")
        Call register(@Body HashMap registerApiPayload);
    }
    

    and a function to set parameters to post data to server(In MainActivity):

    private void Retrofit(){
    
        Retrofit retrofitRequest = new Retrofit.Builder()
                .baseUrl(IHttpRequest.BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
        // set data to send
        HashMap SendData =new HashMap<>();
        SendData.put("token","XYXIUNJHJHJHGJHGJHGRTYTRY");
        SendData.put("contract_type","0");
        SendData.put("StopLess","37000");
        SendData.put("StopProfit","48000");
    
        final IHttpRequest request=retrofitRequest.create(IHttpRequest.class);
    
        request.register(SendData).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (response.isSuccessful()){
                    Toast.makeText(getApplicationContext(),response.body().toString(),Toast.LENGTH_LONG).show();
                }
            }
    
            @Override
            public void onFailure(Call call, Throwable t) {
    
            }
        });
    
    }
    

    And I found Retrofit faster than volley in my case.

提交回复
热议问题