Search code examples
javaokhttp

How to use OKHTTP to make a post request?


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?


Solution

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