OkHttp Post Body as JSON

时间:2015-12-09 13:22:55

标签: android json http-post okhttp ion

所以,当我使用Koush的Ion时,我能够通过一个简单的.setJsonObjectBody(json).asJsonObject()

在我的帖子中添加一个json正文

我正在转向OkHttp,我真的没有看到这样做的好方法。我到处都收到错误400.

有人有什么想法吗?

我甚至尝试将其手动格式化为json字符串。

String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);

String url = mBaseUrl + "/" + id + "/report";

Request request = new Request.Builder()
        .header("X-Client-Type", "Android")
        .url(url)
        .post(RequestBody
                .create(MediaType
                    .parse("application/json"),
                        "{\"Reason\": \"" + reason + "\"}"
                ))
        .build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
    @Override
    public void onFailure(Request request, IOException throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException(
                "Unexpected code " + response);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

/*Ion.with(getContext(), url)
        .setHeader("X-Client-Type", "Android")
        .setJsonObjectBody(json)
        .asJsonObject()
        .setCallback(new FutureCallback<JsonObject>() {
            @Override
            public void onCompleted(Exception e, JsonObject result) {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });*/

编辑:对于后来绊倒这个问题的人来说,这是我的解决方案,它可以异步完成所有事情。所选答案是正确的,但我的代码有点不同。

String reason = menuItem.getTitle().toString();
if (reason.equals("Copyright"))
    reason = "CopyrightInfringement";
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);

String url = mBaseUrl + "/" + id + "/report";

String jsonString = json.toString();
RequestBody body = RequestBody.create(JSON, jsonString);

Request request = new Request.Builder()
    .header("X-Client-Type", "Android")
    .url(url)
    .post(body)
    .build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
    @Override
    public void onFailure(Request request, IOException throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void onResponse(Response response) throws IOException {
        if (!response.isSuccessful()) throw new IOException(
            "Unexpected code " + response);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
            }
        });
    }
});

/*Ion.with(getContext(), url)
    .setHeader("X-Client-Type", "Android")
    .setJsonObjectBody(json)
    .asJsonObject()
    .setCallback(new FutureCallback<JsonObject>() {
        @Override
        public void onCompleted(Exception e, JsonObject result) {
            Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
        }
    });*/

...

private void runOnUiThread(Runnable task) {
    new Handler(Looper.getMainLooper()).post(task);
}

还有一点工作,主要是因为你必须回到UI线程去做任何UI工作,但是你只需要工作就可以获得HTTPS的好处。

4 个答案:

答案 0 :(得分:106)

只需使用const IID IID_S = { 0x0B689485, 0xF347, 0x4414{0xBF,0x86,0x07,0x92,0x6A,0xC2,0x52,0x6C } }; struct Data { double d; int n; SAFEARRAY *S; }; __declspec(dllexport) int __stdcall Cpp_Test2(Data *d) { SAFEARRAYBOUND rgsabound[1]; rgsabound[0].lLbound = 0; rgsabound[0].cElements = 5; IRecordInfo* pRecInfo = NULL; HRESULT hr = GetRecordInfoFromGuids(LIBID_MYLIB, 9, 9, 0, IID_S, &pRecInfo); if (pRecInfo) { d->S = SafeArrayCreateEx(VT_RECORD, 1, rgsabound, pRecInfo); return 1; } return 0; } method即可。 看看OkHttp的教程:

JSONObject.toString();

答案 1 :(得分:7)

另一种方法是使用FormBody.Builder() 这是回调的一个例子:

Callback loginCallback = new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        try {
            Log.i(TAG, "login failed: " + call.execute().code());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // String loginResponseString = response.body().string();
        try {
            JSONObject responseObj = new JSONObject(response.body().string());
            Log.i(TAG, "responseObj: " + responseObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // Log.i(TAG, "loginResponseString: " + loginResponseString);
    }
};

然后,我们创建自己的身体:

RequestBody formBody = new FormBody.Builder()
        .add("username", userName)
        .add("password", password)
        .add("customCredential", "")
        .add("isPersistent", "true")
        .add("setCookie", "true")
        .build();

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(this)
        .build();
Request request = new Request.Builder()
        .url(loginUrl)
        .post(formBody)
        .build();

最后,我们打电话给服务器:

client.newCall(request).enqueue(loginCallback);

答案 2 :(得分:5)

您可以创建自己的JSONObject,然后toString()

请记住在doInBackground中的AsyncTask后台线程中运行它。

   // create your json here
   JSONObject jsonObject = new JSONObject();
   try {
       jsonObject.put("username", "yourEmail@com");
       jsonObject.put("password", "yourPassword");
       jsonObject.put("anyKey", "anyValue");

   } catch (JSONException e) {
       e.printStackTrace();
   }

  OkHttpClient client = new OkHttpClient();
  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  // put your json here
  RequestBody body = RequestBody.create(JSON, jsonObject.toString());
  Request request = new Request.Builder()
                    .url("https://yourUrl/")
                    .post(body)
                    .build();

  Response response = null;
  try {
      response = client.newCall(request).execute();
      String resStr = response.body().string();
  } catch (IOException e) {
      e.printStackTrace();
  }

答案 3 :(得分:1)

在okhttp v4中。*我以这种方式工作了

return RedirectToAction("SomeAction2", "SomeController2", new{id = someid});