Reputation: 193
Here I am trying to post some data to Rest API by adding query parameters using Java but getting response saying bad request.
When I test it from SOAPUI or CURL commands it is working fine.
package com.anergroup;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
public class RestRequestURL {
public void TestRestRequest(){
HttpClient httpclient = new DefaultHttpClient();
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("hostname")
.setPort(8080)
.setPath("/oauth/check_token")
.setParameter("token", "7e9e5b81-1009-49cb-b71f-f418c6b1db3f");
URI uri;
try {
uri = builder.build();
System.out.println("URL Token1 : "+uri);
HttpPost httppost = new HttpPost(uri);
HttpResponse response = httpclient.execute(httppost);
System.out.println("URL Token : "+response);
} catch (URISyntaxException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Response is:
HTTP/1.1 400 Bad Request [Server: Apache-Coyote/1.1, Access-Control-Allow-Origin: *, X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache, Expires: 0, X-Frame-Options: DENY, X-Application-Context: api-gateway-uaa:dev:8080, Cache-Control: no-store, Pragma: no-cache, Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked, Date: Wed, 25 May 2016 15:08:27 GMT, Connection: close]
Upvotes: 0
Views: 5872
Reputation: 74
It looks like you need to actually add the token attribute to the payload of the post, not as a URL argument. That is what the -d option is doing on the Curl.
Easy way to do that is to do something like this
List<NameValuePair> data = new new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("token","7e9e5b81-1009-49cb-b71f-f418c6b1db3f"));
httppost.setEntity(new UrlEncodedFormEnity(data));
[Edit] Looks like you may also need to set the content-type header. Curl adds " content-type application/x-www-form-urlencoded" automatically, so you will need to add this to the post as well.
httppost.addHeader(new BasicHeader("Content-Type","application/x-www-form-urlencoded"));
Upvotes: 0
Reputation: 1146
If your goal is to just be able to send a POST request to a Rest API URL, please check the example code at How to send a POST reqeust in Java and try one of the implementations given there.
Upvotes: 1