在Android中的OKhttp中通过POST请求发送JSON正文

问题描述:

我已经设置了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对象发送到服务器的方式是什么。

在此先感谢。

+1

你可以简单地使用非常普遍的库改造为。使用它你只需要创建一个POJO类,其中包含表示JSON字段的字段并将其作为请求的主体发送。 –

试试这个

添加摇篮取决于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; 
} 
+0

感谢哥们。是工作。 :) +1 – nifCody

+0

很高兴帮助:) – young

只是这样做:

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

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