在Android的OKhttp中通过POST请求发送JSON正文 [英] Sending JSON body through POST request in OKhttp in Android

查看:146
本文介绍了在Android的OKhttp中通过POST请求发送JSON正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置好OkHttpClient并成功将GET请求发送到服务器.而且我还可以将带有空body标签的POST请求发送到服务器.

I have setting up OkHttpClient and successfully sending the GET request to the server. And also I could able to sending the POST request to the server with empty body tag.

现在,我正在尝试将以下JSON对象发送到服务器.

Now, I'm trying to send the following JSON Object to the server.

{
"title": "Mr.",
"first_name":"Nifras",
"last_name": "",
"email": "nfil@gmail.com",
"contact_number": "75832366",
"billing_address": "",
"connected_via":"Application"
}

为此,我尝试添加OkHttpClient库类RequestBody,但是我无法将JSON对象作为http POST请求的正文发送.我尝试通过以下方式构建主体并处理发布请求.

For this I have trying to adding the OkHttpClient library class RequestBody but I fail to sending the JSON object as body of the http POST request. The following way I have try to build the body and process the post request.

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对象发送到服务器的方式是什么.

What is the way I send the JSON object to the server via POST request.

谢谢.

推荐答案

尝试一下

添加Gradle取决于compile 'com.squareup.okhttp3:okhttp:3.2.0'

Add Gradle depends compile 'com.squareup.okhttp3:okhttp:3.2.0'

public static JSONObject foo(String url, JSONObject json) {
        JSONObject jsonObjectResp = null;

        try {

            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();

            okhttp3.RequestBody body = RequestBody.create(JSON, json.toString());
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            okhttp3.Response response = client.newCall(request).execute();

            String networkResp = response.body().string();
            if (!networkResp.isEmpty()) {
                jsonObjectResp = parseJSONStringToJSONObject(networkResp);
            }
        } catch (Exception ex) {
            String err = String.format("{\"result\":\"false\",\"error\":\"%s\"}", ex.getMessage());
            jsonObjectResp = parseJSONStringToJSONObject(err);
        }

        return jsonObjectResp;
    }

解析响应

   private static JSONObject parseJSONStringToJSONObject(final String strr) {

    JSONObject response = null;
    try {
        response = new JSONObject(strr);
    } catch (Exception ex) {
        //  Log.e("Could not parse malformed JSON: \"" + json + "\"");
        try {
            response = new JSONObject();
            response.put("result", "failed");
            response.put("data", strr);
            response.put("error", ex.getMessage());
        } catch (Exception exx) {
        }
    }
    return response;
}

这篇关于在Android的OKhttp中通过POST请求发送JSON正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆