我已经设置了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对象发送到服务器的方式是什么。
提前致谢。
答案 0 :(得分:7)
试试这个
添加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;
}
答案 1 :(得分:1)
这样做:
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8(yourJsonString);
}
它应该可以正常工作:-)如果我正确理解文档,sink
是一个容器,您可以在其中编写要发布的数据。 writeUtf8
方法可以方便地使用UTF-8编码将String
转换为字节。