0

I have found this example below to send HTTP POST message with OKHttp.

I do not understand how to pass a body string to RequestBody. Why it takes two argument?

RequestBody formBody = new FormBody.Builder()
                .add("message", "Your message")
                .build();
        Request request = new Request.Builder()
                .url("http://rhcloud.com")
                .post(formBody).addHeader("operation", "modifyRecords")
                .build();

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try (ResponseBody responseBody = response.body()) {
                        if (!response.isSuccessful())
                            throw new IOException("Unexpected code " + response);

                        Headers responseHeaders = response.headers();
                        for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                        }

                        System.out.println(responseBody.string());
                    }
                }
            });
        }
    }
János
  • 32,867
  • 38
  • 193
  • 353

1 Answers1

2

I'm not sure if I understand what you mean quite right, but if you are asking why the FormBody .add() takes two arguments, it's because these are Key-Value-Pairs. The first parameter is the name and the second the value.

Anyway I think this example shows a clearer way how to post a string:

  public static final MediaType MEDIA_TYPE_MARKDOWN
      = MediaType.parse("text/x-markdown; charset=utf-8");

  private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    String postBody = ""
        + "Releases\n"
        + "--------\n"
        + "\n"
        + " * _1.0_ May 6, 2013\n"
        + " * _1.1_ June 15, 2013\n"
        + " * _1.2_ August 11, 2013\n";

    Request request = new Request.Builder()
        .url("https://api.github.com/markdown/raw")
        .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
        .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
  }
Brudus
  • 749
  • 1
  • 8
  • 22
  • I just want to send a JSON. What `MediaType` I need to set? – János Sep 09 '16 at 12:01
  • 1
    I think this: http://stackoverflow.com/questions/34179922/okhttp-post-body-as-json could be helpful. The author of this post added a solution. I haven't worked for a while with OkHttp. Anyway MediaType must be application/json – Brudus Sep 09 '16 at 12:08
  • The right line I need is: `RequestBody formBody = RequestBody.create(MediaType.parse("application/json"), "[\"MB\", [], []]");` – János Sep 09 '16 at 12:14
  • Great! Glad to hear that! – Brudus Sep 09 '16 at 12:16