37

In my Android application, I am using okHttp library. How can I send parameters to the server(api) using the okhttp library? currently I am using the following code to access the server now need to use the okhttp library.

this is the my code:

httpPost = new HttpPost("http://xxx.xxx.xxx.xx/user/login.json");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID));
nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord));
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());
M.A.Murali
  • 9,988
  • 36
  • 105
  • 182

9 Answers9

53

For OkHttp 3.x, FormEncodingBuilder was removed, use FormBody.Builder instead

        RequestBody formBody = new FormBody.Builder()
                .add("email", "Jurassic@Park.com")
                .add("tel", "90301171XX")
                .build();

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        Response response = client.newCall(request).execute();
        return response.body().string();
Bao Le
  • 16,643
  • 9
  • 65
  • 68
  • 1
    How can I add keys & params to formBody ? I get both "email" and "Jurassic@Park.com" dynamically and I have to have a RequestBody. Thanks. – Alvin Mar 09 '16 at 08:07
  • @Alvin Yes, definitely. Just do it in such way, `RequestBody formBody = new FormBody.Builder() .add(dynamicEmailKey, dynamicEmailParam) .build();` – Farid May 05 '16 at 06:59
  • @Bao Le, why isn't version 3.x available on [mvnrepository.com](http://mvnrepository.com/artifact/com.squareup.okhttp/okhttp)? – Ein Doofus May 25 '16 at 21:12
  • okhttp3 uses persistent versioning and puts the version in the group id and package names http://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp – sam Sep 08 '17 at 13:38
  • 3
    Other solutions are based on older versions of OkHttp. This one is the most updated. – DYS Jun 29 '18 at 12:48
46
    private final OkHttpClient client = new OkHttpClient();

      public void run() throws Exception {
        RequestBody formBody = new FormEncodingBuilder()
            .add("email", "Jurassic@Park.com")
            .add("tel", "90301171XX")
            .build();
        Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(formBody)
            .build();

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

        System.out.println(response.body().string());
      }
Gennady Kozlov
  • 1,011
  • 1
  • 11
  • 11
7

You just need to format the body of the POST before creating the RequestBody object.

You could do this manually, but I'd suggest you use the MimeCraft library from Square (makers of OkHttp).

In this case you'd need the FormEncoding.Builder class; set the contentType to "application/x-www-form-urlencoded" and use add(name, value) for each key-value pair.

matiash
  • 54,791
  • 16
  • 125
  • 154
  • While your are checking out MimeCraft, you might want to check out Retrofit (also by Square) if your ultimate goal is a Restful api – nPn Jun 15 '14 at 21:29
  • does this work with `get` requests as well? I mean when `FormEncoding.Builder` is used with `get` requests, are the parameters added to the url? – Writwick Apr 05 '15 at 18:02
  • To answer my own question, when `FormEncoding.Builder` is used with `GET` requests, `OkHttp` throws an exception something like `GET requests doesn't support request body`. – Writwick Apr 06 '15 at 04:17
5

None of the answers worked for me, so I played around and below one worked fine. Sharing just in case someone gets stuck with the same issue:

Imports:

import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

Code:

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
        .type(MultipartBuilder.FORM) //this is what I say in my POSTman (Chrome plugin)
        .addFormDataPart("name", "test")
        .addFormDataPart("quality", "240p")
        .build();
Request request = new Request.Builder()
        .url(myUrl)
        .post(requestBody)
        .build();
try {
    Response response = client.newCall(request).execute();
    String responseString = response.body().string();
    response.body().close();
    // do whatever you need to do with responseString
}
catch (Exception e) {
    e.printStackTrace();
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
3

Usually to avoid Exceptions brought about by the code running in UI thread, run the request and response process in a worker thread (Thread or Asynch task) depending on the anticipated length of the process.

    private void runInBackround(){

       new Thread(new Runnable() {
            @Override
            public void run() { 
                //method containing process logic.
                makeNetworkRequest(reqUrl);
            }
        }).start();
    }

    private void makeNetworkRequest(String reqUrl) {
       Log.d(TAG, "Booking started: ");
       OkHttpClient httpClient = new OkHttpClient();
       String responseString = "";

       Calendar c = Calendar.getInstance();
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       String booked_at = sdf.format(c.getTime());

         try{
             RequestBody body = new FormBody.Builder()
                .add("place_id", id)
                .add("booked_at", booked_at)
                .add("booked_by", user_name.getText().toString())
                .add("booked_from", lat+"::"+lng)
                .add("phone_number", user_phone.getText().toString())
                .build();

        Request request = new Request.Builder()
                .url(reqUrl)
                .post(body)
                .build();

        Response response = httpClient
                .newCall(request)
                .execute();
        responseString =  response.body().string();
        response.body().close();
        Log.d(TAG, "Booking done: " + responseString);

        // Response node is JSON Object
        JSONObject booked = new JSONObject(responseString);
        final String okNo = booked.getJSONArray("added").getJSONObject(0).getString("response");
        Log.d(TAG, "Booking made response: " + okNo);

        runOnUiThread(new Runnable()
        {
            public void run()
            {
                if("OK" == okNo){
                    //display in short period of time
                    Toast.makeText(getApplicationContext(), "Booking Successful", Toast.LENGTH_LONG).show();
                }else{
                    //display in short period of time
                    Toast.makeText(getApplicationContext(), "Booking Not Successful", Toast.LENGTH_LONG).show();
                }
            }
        });

    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

}

I hope it helps someone there.

orups
  • 59
  • 5
2

Another way (without MimeCraft), is to do :

    parameters = "param1=text&param2=" + param2  // for example !
    request = new Request.Builder()
            .url(url + path)
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
            .build();

and declare :

    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
Christian
  • 748
  • 7
  • 23
0

(Kotlin version) You would need:

...
val formBody = FormBody.Builder()
    .add("your_key", "your_value")
    .build()
val newRequest: Request.Builder = Request.Builder()
    .url("api_url")
    .addHeader("Content-Type", "application/x-www-form-urlencoded")
    .post(formBody)
...

Then, if you have a nodejs express server with npm body-parser installed, be sure to do following:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
...
Tô Minh Tiến
  • 1,131
  • 11
  • 6
0

Kotlin Version:

fun requestData(url: String): String {

    var formBody: RequestBody = FormBody.Builder()
        .add("email", "Jurassic@Park.com")
        .add("tel", "90301171XX")
        .build();

    var client: OkHttpClient = OkHttpClient();
    var request: Request = Request.Builder()
        .url(url)
        .post(formBody)
        .build();

    var response: Response = client.newCall(request).execute();
    return response.body?.toString()!!
}
Ali A. Jalil
  • 873
  • 11
  • 25
-1

If you want to send Post data through API using OKHTTP 3 please try below simple code

MediaType MEDIA_TYPE = MediaType.parse("application/json");
        String url = "https://cakeapi.trinitytuts.com/api/add";

        OkHttpClient client = new OkHttpClient();

        JSONObject postdata = new JSONObject();
        try {
            postdata.put("username", "name");
            postdata.put("password", "12345");
        } catch(JSONException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .header("Accept", "application/json")
                .header("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                //call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String mMessage = response.body().string();
                Log.e(TAG, mMessage);
            }
        });

You can read the complete tutorial to send data to server using OKHTTP 3 GET and POST request here:- https://trinitytuts.com/get-and-post-request-using-okhttp-in-android-application/

Aneh Thakur
  • 1,072
  • 12
  • 20