如何使用Retrofit提交参数数组?技术实现咨询
First, let's address the core issue: your current Retrofit interface uses @FormUrlEncoded, which is intended for form-data submissions, but your target API expects a JSON request body. Here's the cleanest way to fix this:
Step 1: Create Model Classes for the Request Structure
You need to define POJO classes that mirror the JSON structure your API expects.
1.1 The Top-Level Request Class
This represents the entire JSON payload:
public class ApiRequest { private String ProcName; private List<TransferCenterStoreParameters> Parameters; // Constructor for easy initialization public ApiRequest(String procName, List<TransferCenterStoreParameters> parameters) { this.ProcName = procName; this.Parameters = parameters; } // Getters and Setters (or use Lombok to auto-generate these) public String getProcName() { return ProcName; } public void setProcName(String procName) { ProcName = procName; } public List<TransferCenterStoreParameters> getParameters() { return Parameters; } public void setParameters(List<TransferCenterStoreParameters> parameters) { Parameters = parameters; } }
1.2 The Parameters Class
Ensure your existing TransferCenterStoreParameters matches the required structure:
public class TransferCenterStoreParameters { private String Name; private String Value; public TransferCenterStoreParameters(String name, String value) { this.Name = name; this.Value = value; } // Getters and Setters public String getName() { return Name; } public void setName(String name) { Name = name; } public String getValue() { return Value; } public void setValue(String value) { Value = value; } }
Step 2: Update Your Retrofit Interface
Replace @FormUrlEncoded and @Field with @Body to send the entire JSON payload:
@POST("GetDispatchList") Call<TransferCenterStoreResponse> TRANSFER_CENTER_STORE_RESPONSE_CALL( @Header("Authorization") String authHeader, @Body ApiRequest requestBody );
This tells Retrofit to serialize the ApiRequest object directly into JSON, which exactly matches the format your API needs.
Step 3: Configure Retrofit with a JSON Converter
Make sure your Retrofit instance uses a converter (like Gson) to handle JSON serialization/deserialization:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("YOUR_BASE_API_URL") .addConverterFactory(GsonConverterFactory.create()) // Required for JSON handling .build();
Step 4: Make the API Call
Here's how to use the updated interface to send the request:
// 1. Create the parameters list List<TransferCenterStoreParameters> params = new ArrayList<>(); params.add(new TransferCenterStoreParameters("StoreCode", "B201")); // 2. Build the request body ApiRequest request = new ApiRequest("BR_SP_BRN_GET_STORE_ACTIVE_SHIPMENTS", params); // 3. Get your API service instance YourApiService apiService = retrofit.create(YourApiService.class); // 4. Execute the call Call<TransferCenterStoreResponse> call = apiService.TRANSFER_CENTER_STORE_RESPONSE_CALL("Bearer YOUR_AUTH_TOKEN", request); call.enqueue(new Callback<TransferCenterStoreResponse>() { @Override public void onResponse(Call<TransferCenterStoreResponse> call, Response<TransferCenterStoreResponse> response) { if (response.isSuccessful()) { // Handle successful response TransferCenterStoreResponse responseData = response.body(); // Do something with the data } else { // Handle error responses (e.g., 4xx, 5xx) String errorBody = response.errorBody() != null ? response.errorBody().toString() : "Unknown error"; // Log or display error } } @Override public void onFailure(Call<TransferCenterStoreResponse> call, Throwable t) { // Handle network failures (e.g., no internet) t.printStackTrace(); } });
Alternative: If You Must Use Form-Encoded Data
If for some reason you can't switch to a JSON body (not recommended), you can serialize the parameters list to a JSON string manually and pass it as a form field:
// Updated interface @FormUrlEncoded @POST("GetDispatchList") Call<TransferCenterStoreResponse> TRANSFER_CENTER_STORE_RESPONSE_CALL( @Header("Authorization") String authHeader, @Field("ProcName") String procName, @Field("Parameters") String parametersJson ); // Usage Gson gson = new Gson(); List<TransferCenterStoreParameters> params = new ArrayList<>(); params.add(new TransferCenterStoreParameters("StoreCode", "B201")); String paramsJson = gson.toJson(params); Call<TransferCenterStoreResponse> call = apiService.TRANSFER_CENTER_STORE_RESPONSE_CALL( "Bearer YOUR_AUTH_TOKEN", "BR_SP_BRN_GET_STORE_ACTIVE_SHIPMENTS", paramsJson );
Note: This only works if your API accepts the Parameters field as a JSON string in form-data. The first approach (JSON body) is the correct way to match the request format you provided.
内容的提问来源于stack exchange,提问作者cartoonworld

