I have used this method https://stackoverflow.com/a/31744565/5829906 but doesnt post data.
Here is my code
OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome") .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try { Response response = client.newCall(request).execute(); String responseString = response.body().string(); response.body().close(); }catch (Exception e) { e.printStackTrace(); }
I tried DefaultHttpClient , that seems to be working, but it shows deprecated, so thought of trying something different..Cant figure out what is wrong in this
Create a MediaType variable named FORM: public static final MediaType FORM = MediaType. parse("multipart/form-data"); Create a RequestBody using the FORM variable and your unparsed params (String):
Beginning with Mobile SDK 4.2, the Android REST request system uses OkHttp (v3. 2.0), an open-source external library from Square Open Source, as its underlying architecture. This library replaces the Google Volley library from past releases.
You select MediaType MultipartBuilder.FORM
which is for uploading the file/image as multipart
public static final MediaType FORM = MediaType.parse("multipart/form-data");
try to send like this as
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With