Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OKHTTP to make a post request?

Tags:

java

okhttp

I read some examples which are posting jsons to the server.

some one says :

OkHttp is an implementation of the HttpUrlConnection interface provided by Java. It provides an input stream for writing content and doesn't know (or care) about what format that content is.

Now I want to make a normal post to the URL with params of name and password.

It means I need to do encode the name and value pair into stream by myself?

like image 770
user2219372 Avatar asked May 04 '14 12:05

user2219372


People also ask

How does OkHttp send raw data?

Create a MediaType variable named FORM: public static final MediaType FORM = MediaType. parse("multipart/form-data"); Create a RequestBody using the FORM variable and your unparsed params (String):

What is the use of OkHttp?

OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.


2 Answers

As per the docs, OkHttp version 3 replaced FormEncodingBuilder with FormBody and FormBody.Builder(), so the old examples won't work anymore.

Form and Multipart bodies are now modeled. We've replaced the opaque FormEncodingBuilder with the more powerful FormBody and FormBody.Builder combo.

Similarly we've upgraded MultipartBuilder into MultipartBody, MultipartBody.Part, and MultipartBody.Builder.

So if you're using OkHttp 3.x try the following example:

OkHttpClient client = new OkHttpClient();

RequestBody formBody = new FormBody.Builder()
        .add("message", "Your message")
        .build();
Request request = new Request.Builder()
        .url("https://www.example.com/index.php")
        .post(formBody)
        .build();

try {
    Response response = client.newCall(request).execute();

    // Do something with the response.
} catch (IOException e) {
    e.printStackTrace();
}
like image 184
Mauker Avatar answered Oct 19 '22 16:10

Mauker


The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("somParam", "someValue")
        .build();

Request request = new Request.Builder()
        .url(BASE_URL + route)
        .post(requestBody)
        .build();
like image 110
Islam Abdalla Avatar answered Oct 19 '22 14:10

Islam Abdalla