Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I post data using okhttp library with content type x-www-form-urlencoded?

Tags:

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

like image 216
MrRobot9 Avatar asked Mar 02 '16 19:03

MrRobot9


People also ask

How does OkHttp send raw data?

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):

What is the underlying library of OkHttp?

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.


1 Answers

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());  } 

like image 176
Chayon Ahmed Avatar answered Sep 22 '22 23:09

Chayon Ahmed