okHTTP POST 请求正文有很多孩子

okHTTP POST request body with many childs

我正在使用运营商的收费 API,并且必须通过 API 调用传递以下 JSON 格式。我正在使用 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 错误请求

试试这将根据您的需要格式化您的 body

 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();