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 ();
}
});