【问题标题】:Sending JSON body through POST request in OKhttp in Android在 Android 的 OKhttp 中通过 POST 请求发送 JSON 正文
【发布时间】:2017-03-24 06:23:49
【问题描述】:

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

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

{
"title": "Mr.",
"first_name":"Nifras",
"last_name": "",
"email": "nfil@gmail.com",
"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 对象发送到服务器的方式是什么。

提前致谢。

【问题讨论】:

  • 您可以简单地使用非常流行的 Retrofit 库。使用它,您只需要创建一个带有表示 JSON 字段的字段的 POJO 类,并将其作为请求的正文发送。

标签: android json okhttp3 okhttp


【解决方案1】:

这样做:

@Override
public void writeTo(BufferedSink sink) throws IOException {
     sink.writeUtf8(yourJsonString); 
}

它应该可以正常工作 :-) 如果我正确理解文档,sink 是一个容器,您可以在其中写入要发布的数据。 writeUtf8 方法便于将String 转换为字节,使用UTF-8 编码。

【讨论】:

    【解决方案2】:

    试试这个

    添加 Gradle 依赖 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;
    }
    

    【讨论】:

    • 很高兴它有帮助:)
    • 谢谢老兄@young
    • 我还有一个问题要问你。如何在改造中包括这个? @年轻
    猜你喜欢
    • 2015-07-24
    • 2019-09-12
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多