How to send a JSON object over Request with Android?

前端 未结 8 2053
慢半拍i
慢半拍i 2020-11-22 03:32

I want to send the following JSON text

{\"Email\":\"aaa@tbbb.com\",\"Password\":\"123456\"}

to a web service and read the response. I kno

8条回答
  •  难免孤独
    2020-11-22 03:53

    Nothing could be simple than this. Use OkHttpLibrary

    Create your json

    JSONObject requestObject = new JSONObject();
    requestObject.put("Email", email);
    requestObject.put("Password", password);
    

    and send it like this.

    OkHttpClient client = new OkHttpClient();
    
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
                .addHeader("Content-Type","application/json")
                .url(url)
                .post(requestObject.toString())
                .build();
    
    okhttp3.Response response = client.newCall(request).execute();
    

提交回复
热议问题