如何使用okhttp在jsonarray中发布form.body?

vdgimpew  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(334)

嗨,伙计们,我想发一个 JSONArray 使用okhttp。我想这样做:

[
  {
    "name": "john"
  },
  {
    "food": "burger"
  }
]

有人能帮我吗?

50few1ms

50few1ms1#

像这样:

public void sendRequest(String route) {
    OkHttpClient client = new OkHttpClient();
    String url = baseUrl + route;

    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("username", String.valueOf(username.getText()))
            .addFormDataPart("password", String.valueOf(password.getText()))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("Error", "Something Went Wrong");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String myresponse = response.body().string();
                try {
                    JSONArray all = new JSONArray(myresponse);
                    // Do whatever
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                String errorBodyString = response.body().string();
                Log.d("Error", errorBodyString);
            }
        }
    });
}
yeotifhr

yeotifhr2#

你可以尝试添加 JSONObject 在数组中,然后将其传递给 JSONArray .
像这样:

JSONArray list = new JSONArray();

JSONObject js = new JSONObject();
try {
    js.put("name", "john");
} catch (JSONException e) {
    e.printStackTrace();
}
list.put(js);

js = new JSONObject();
try {
    js.put("food", "burger");
} catch (JSONException e) {
    e.printStackTrace();
}
list.put(js);

Log.e(TAG, "found json array " + list);

如果你有更多的项目,那么在循环中运行'js',直到你完成它。

相关问题