我正在使用运营商提供的收费API,并且以下JSON格式必须与API调用一起传递。我正在使用okHTTP库。
String telNum = "+941234567";
String pbody = "{\"amountTransaction\": {\"clientCorrelator\": \"7659\",\"endUserId\": \"tel:"+telNum+"\",\"paymentAmount\": {\"chargingInformation\": {\"amount\": 1,\"currency\": \"LKR\",\"description\": \"Test Charge\"},\"chargingMetaData\": {\"onBehalfOf\": \"IdeaBiz Test\",\"purchaseCategoryCode\": \"Service\",\"channel\": \"WAP\",\"taxAmount\": \"0\",\"serviceID\": \"theserviceid\"}},\"referenceCode\": \"REF-12345\",\"transactionOperationStatus\": \"Charged\"}}";```
以下是JSON格式的方式。
{
"amountTransaction": {
"clientCorrelator": "54321",
"endUserId": "tel:+94761234567",
"paymentAmount": {
"chargingInformation": {
"amount": 1,
"currency": "LKR",
"description": "Test Charge"
},
"chargingMetaData": {
"onBehalfOf": "IdeaBiz Test",
"purchaseCategoryCode": "Service",
"channel": "WAP",
"taxAmount": "0",
"serviceID": "null"
}
},
"referenceCode": "REF-12345",
"transactionOperationStatus": "Charged"
}
}
我收到错误400错误的请求
尝试此操作将根据您的身体要求格式化
try {
JSONObject jsonObject = new JSONObject(pbody);
pbody=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
OkHTTP需要RequestBody
的POST
对象,所以尝试这个:
RequestBody body = RequestBody.create(MediaType.APPLICATION_JSON, pbody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
您可以使用ObjectMapper
将String
转换为Map
:
ObjectMapper objectMapper = new ObjectMapper(); // package: com.fasterxml.jackson.databind
Map body = objectMapper.readValue(pbody, Map.class); // you need to handle IOException
现在尝试将此Map
而不是String
作为主体传递给API。我希望它能解决问题。