Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add parameters to api (http post) using okhttp library in Android

Tags:

android

okhttp

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()); 
like image 698
M.A.Murali Avatar asked Jun 15 '14 20:06

M.A.Murali


People also ask

How do I use OkHttp on Android?

OkHttp Query Parameters ExampleBuilder urlBuilder = HttpUrl. parse("https://httpbin.org/get).newBuilder(); urlBuilder. addQueryParameter("website", "www.journaldev.com"); urlBuilder. addQueryParameter("tutorials", "android"); String url = urlBuilder.

What is OkHttp library?

Overview. OkHttp is a third-party library developed by Square for sending and receive HTTP-based network requests. It is built on top of the Okio library, which tries to be more efficient about reading and writing data than the standard Java I/O libraries by creating a shared memory pool.


2 Answers

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

        RequestBody formBody = new FormBody.Builder()                 .add("email", "[email protected]")                 .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(); 
like image 128
Bao Le Avatar answered Sep 29 '22 21:09

Bao Le


    private final OkHttpClient client = new OkHttpClient();        public void run() throws Exception {         RequestBody formBody = new FormEncodingBuilder()             .add("email", "[email protected]")             .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());       } 
like image 20
Gennady Kozlov Avatar answered Sep 29 '22 20:09

Gennady Kozlov