我已經設置了OkHttpClient併成功地將GET請求發送到服務器。而且我也可以將POST請求發送給空身標籤的服務器。在Android中的OKhttp中通過POST請求發送JSON正文
現在,我試圖將以下JSON對象發送到服務器。
{
"title": "Mr.",
"first_name":"Nifras",
"last_name": "",
"email": "[email protected]",
"contact_number": "75832366",
"billing_address": "",
"connected_via":"Application"
}
爲此,我已經試圖加入OkHttpClient庫類RequestBody
但我不能發送JSON對象作爲HTTP POST請求的身體。以下方式我嘗試構建正文並處理髮布請求。
OkHttpClient client = new OkHttpClient();
RequestBody body = new RequestBody() {
@Override
public MediaType contentType() {
return ApplicationContants.JSON;
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
// This is the place to add json I thought. But How could i do this
}
};
Request request = new Request.Builder()
.url(ApplicationContants.BASE_URL + ApplicationContants.CUSTOMER_URL)
.post(body)
.build();
我通過POST請求將JSON對象發送到服務器的方式是什麼。
在此先感謝。
你可以簡單地使用非常普遍的庫改造爲。使用它你只需要創建一個POJO類,其中包含表示JSON字段的字段並將其作爲請求的主體發送。 –