0

If you want to do an HTTP Post with parameters and have it be sent with a content type of "x-www-form-urlencoded" then the way to do that in Apache HTTP Client 3 is...

    HttpMethod method = new PostMethod(myUrl)

    method.setParams(mp)
    method.addParameter("user_name", username)
    method.addParameter("password", password)

    method.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')

    int responseCode = httpClient.executeMethod(method)

But Apache HTTP Client 4 introduced the UrlEncodedFormEntity object, so the new way of doing the same there is...

HttpPost post = new HttpPost(url);

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user_name", username));
urlParameters.add(new BasicNameValuePair("password", password));;

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);

What purpose does this UrlEncodedFormEntity object serve other than setting the content type to "x-www-form-urlencoded"?

The docs say it creates an "An entity composed of a list of url-encoded pairs", but can't that be done just by setting the content type?

AbuMariam
  • 2,582
  • 7
  • 34
  • 64
  • Check this https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data – Sambit Jun 05 '19 at 18:31
  • Also you can check https://stackoverflow.com/questions/26723467/what-is-the-difference-between-form-data-x-www-form-urlencoded-and-raw-in-the-p/36452270 – Sambit Jun 05 '19 at 18:31

1 Answers1

1

The HttpEntity interface is the top-level interface controlling how the body of the request/response is handled. In this case, you're using a UrlEncodedFormEntity which knows how to encode the parameters and output them in the required format.

jspcal
  • 47,335
  • 4
  • 66
  • 68