这个问题以前可能被问过,但没有明确的答案。如何在Retrofit请求的主体中发布原始的整个JSON ?
在这里看到类似的问题。或者这个答案是正确的,它必须是表单url编码并作为一个字段传递?我真的希望不是,因为我要连接的服务只是希望在文章正文中有原始JSON。它们不是用来为JSON数据寻找特定字段的。
I just want to clarify this with the restperts once and for all. One person answered not to use Retrofit. The other was not certain of the syntax. Another thinks yes it can be done but only if its form url-encoded and placed in a field (that's not acceptable in my case). No, I can't re-code all the services for my Android client. And yes, it's very common in major projects to post raw JSON instead of passing over JSON content as field property values. Let's get it right and move on. Can someone point to the documentation or example that shows how this is done? Or provide a valid reason why it can/should not be done.
更新:有一件事我可以百分之百确定。你可以在谷歌的Volley中做到这一点。这是与生俱来的。我们可以在Retrofit中这样做吗?
火通话
@Headers("Content-Type: application/json")
@POST("/set_data")
Call<CommonResponse> setPreferences(@Body RequestData request);
注意:使用Retrofit的GSON库
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;
}
}
我想这将有所帮助,您可能已经拥有了所有集成,我们不需要任何花哨的东西来使用上面的代码片段。它非常适合我。
我想比较排射的速度和改装的发送和接收数据,我写在下面的代码(改装部分)
第一个依赖:
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
}
然后界面:
public interface IHttpRequest {
String BaseUrl="https://example.com/api/";
@POST("NewContract")
Call<JsonElement> register(@Body HashMap registerApiPayload);
}
和一个函数来设置参数,张贴数据到服务器(在MainActivity):
private void Retrofit(){
Retrofit retrofitRequest = new Retrofit.Builder()
.baseUrl(IHttpRequest.BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
// set data to send
HashMap<String,String> 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<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response.isSuccessful()){
Toast.makeText(getApplicationContext(),response.body().toString(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
}
});
}
对我来说,改装比截击更快。