我如何在我的截击请求正文中发送此请求, 提前致谢
{
"amount": "000",
"card": {
"number": "00000",
"expiry_month": "00",
"expiry_year": "00",
"cvv": "000",
"pin": "000"
}
}
这是我的请求参数,我已经尝试过,API 告诉我无效参数,请帮帮我
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", User_Token);
headers.put("Content-Type", "application/json");
return headers;
}
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public byte[] getBody() {
Map<String, String> params = new HashMap<String, String>();
params.put( "amount", amount);
params.put( "card", String.valueOf(come()));
return new JSONObject(params).toString().getBytes();
}
private byte[] come() {
Map<String, String> params = new HashMap<String, String>();
params.put( "number", number);
params.put( "expiry_month", month);
params.put( "expiry_year", year);
params.put( "cvv", cvv);
params.put( "pin", pin);
return new JSONObject(params).toString().getBytes();
}
最佳答案
使用 JsonObject
而不是:创建 Map
,将其转换为 Byte[]
,然后获取其 String.valueOf( ...)
。
这将允许您将完整的对象作为请求的正文发送,而不是现在发送的不完整的正文: {"amount":"000","card":"[B@a2e.. .."}
)
为 "card"
: "[B@a2e...."
发送的值的问题在于它不是对象的表示以其属性。相反,它只是您创建的字节数组的内存地址。
在您的代码中,使用 JsonObject
作为对象,并且仅在 getBody()
方法末尾转换为 Byte[]
,因为这是您最终返回完整对象的地方:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", User_Token);
// headers.put("Content-Type", "application/json"); // This is probably redundant, as you are already setting it on getBodyContentType()
return headers;
}
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public byte[] getBody() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("amount", amount);
jsonObject.put("card", come());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString().getBytes();
}
private JSONObject come() throws JSONException {
JSONObject params = new JSONObject();
params.put( "number", number);
params.put( "expiry_month", month);
params.put( "expiry_year", year);
params.put( "cvv", cvv);
params.put( "pin", pin);
return params;
}
关于java - 如何在请求正文中发送嵌套的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45509669/