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 acces
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();
}
Another way (without MimeCraft), is to do :
parameters = "param1=text¶m2=" + 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");
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());
}
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/
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.
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();