How to add parameters to api (http post) using okhttp library in Android
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());
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();
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());
}
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.