What is wrong with this POST request implementation?
A bit more generic and unified method for sending UrlEncoded request:
@SneakyThrows
public String postUrlEncoded(String context, Map<String, String> body) {
List<NameValuePair> nameValuePairs = body.entrySet()
.stream()
.map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
HttpResponse response = Request.Post(baseUrl + context)
.bodyForm(nameValuePairs)
.execute().returnResponse();
return EntityUtils.toString(response.getEntity());
}
Ps: it requires fluent Apache HTTP client. Pom dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
<version>${fluent-hc.version}</version>
</dependency>
You should be using UrlEncodedFormEntity
not setParameter on the post.
It handles the Content-Type: application/x-www-form-urlencoded
header for you too.
HttpPost post = new HttpPost("https://accounts.google.com/o/oauth2/token");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("code", code));
nvps.add(new BasicNameValuePair("client_id", client_id));
nvps.add(new BasicNameValuePair("client_secret", client_secret));
nvps.add(new BasicNameValuePair("redirect_uri", redirect_uri));
nvps.add(new BasicNameValuePair("grant_type", grant_type));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);