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
I particularly like Jake's suggestion of the TypedString
subclass above. You could indeed create a variety of subclasses based on the sorts of POST data you plan to push up, each with its own custom set of consistent tweaks.
You also have the option of adding a header annotation to your JSON POST methods in your Retrofit API…
@Headers( "Content-Type: application/json" )
@POST("/json/foo/bar/")
Response fubar( @Body TypedString sJsonBody ) ;
…but using a subclass is more obviously self-documenting.
@POST("/json/foo/bar")
Response fubar( @Body TypedJsonString jsonBody ) ;
For more clarity on the answers given here, this is how you can use the extension functions. This is only if you are using Kotlin
If you are using com.squareup.okhttp3:okhttp:4.0.1
the older methods of creating objects of MediaType and RequestBody have been deprecated and cannot be used in Kotlin.
If you want to use the extension functions to get a MediaType object and a ResponseBody object from your strings, firstly add the following lines to the class in which you expect to use them.
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
You can now directly get an object of MediaType this way
val mediaType = "application/json; charset=utf-8".toMediaType()
To get an object of RequestBody first convert the JSONObject you want to send to a string this way. You have to pass the mediaType object to it.
val requestBody = myJSONObject.toString().toRequestBody(mediaType)
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<User> getUser(@Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
@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<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(Call<User> call, Response<User> response) {
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
}
API Call
@Headers("Content-Type: application/json")
@POST("/set_data")
Call<CommonResponse> setPreferences(@Body RequestData request);
Note: Use GSON library of Retrofit
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class RequestData {
@SerializedName("access_token")
@Expose
private String accessToken;
@SerializedName("data")
@Expose
private Data data;
// The above 'Data' is another similar class to add inner JSON objects. JSONObject within a JSONObject.
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setData(Data data) {
this.data = data;
}
}
I guess that will help, rest all integration you might already have had and we don't need anything fancy to use above code snippet. It's working perfectly for me.
Using JsonObject
is the way it is:
Create your interface like this:
public interface laInterfaz{
@POST("/bleh/blah/org")
void registerPayer(@Body JsonObject bean, Callback<JsonObject> callback);
}
Make the JsonObject acording to the jsons structure.
JsonObject obj = new JsonObject();
JsonObject payerReg = new JsonObject();
payerReg.addProperty("crc","aas22");
payerReg.addProperty("payerDevManufacturer","Samsung");
obj.add("payerReg",payerReg);
/*json/*
{"payerReg":{"crc":"aas22","payerDevManufacturer":"Samsung"}}
/*json*/
Call the service:
service.registerPayer(obj, callBackRegistraPagador);
Callback<JsonObject> callBackRegistraPagador = new Callback<JsonObject>(){
public void success(JsonObject object, Response response){
System.out.println(object.toString());
}
public void failure(RetrofitError retrofitError){
System.out.println(retrofitError.toString());
}
};
And that its! In my personal opinion, its a lot better than making pojos and working with the class mess. This is a lot more cleaner.