Home java OkHttp 3 for Beginners

OkHttp 3 for Beginners

Author

Date

Category

Hello everyone. Recently I started to study Java for android and many questions arose. One of them is that I cannot figure out how to send a post request using the OkHttp3 library. Simple post without json. If there are examples, tutorials, etc. I would like to read.


Answer 1, authority 100%

// send a request through the client
OkHttpClient client = new OkHttpClient ();
// put the request parameters in the formBody
RequestBody formBody = new FormBody.Builder ()
    .add ("message", "Your message")
    .build ();
// create a request specifying the address and parameters
Request request = new Request.Builder ()
    .url ("http://www.foo.bar/index.php")
    .post (formBody)
    .build ();
// execute the request synchronously, in the thread in which we call execute
try {
  Response response = client.newCall (request) .execute ();
  String serverAnswer = response.body (). String ();
} catch (IOException e) {
  e.printStackTrace ();
}
// execute the request asynchronously
client.newCall (request) .enqueue (new Callback () {
  @Override
  public void onFailure (Request request, IOException e) {
    //IMPORTANT! This is not the main thread, you cannot change the UI from here, you need to switch to the UI thread
    e.printStackTrace ();
  }
  @Override
  public void onResponse (Response response) throws IOException {
    //IMPORTANT! This is not the main thread, you cannot change the UI from here, you need to switch to the UI thread
    String serverAnswer = response.body (). String ();
  }
});

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions