Reputation: 89
I have a RESTful API that I can call by doing the following:
curl -H "Content-Type: application/json" -d '{"url":"http://www.example.com"}' http://www.example.com/post
In Java, when I print out the received request data from the cURL, I correctly get the following data:
Log: Data grabbed for POST data: {"url":"http://www.example.com/url"}
But when I send a POST request via Java using HttpClient/HttpPost, I am getting poorly formatted data that does not allow me to grab the key-value from the JSON.
Log: Data grabbed for POST data: url=http%3A%2F%2Fwww.example.com%2Furl
In Java, I am doing this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nvp1 = new BasicNameValuePair("url", "http://www.example.com/url);
nameValuePairs.add(nvp1);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
How do I make it so that the request from Java is similar to cURL in terms of how the data is sent?
Upvotes: 1
Views: 982
Reputation: 181714
The data you present as coming from the Java client are URL-encoded. You appear to specifically request that by using a UrlEncodedFormEntity
. It is not essential for the body of a POST request to be URL-encoded, so if you don't want that then use a more appropriate HttpEntity
implementation.
In fact, if you want to convert generic name/value pairs to a JSON-format request body, as it seems you do, then you probably need either to use a JSON-specific HttpEntity
implementation or to use a plainer implementation that allows you to format the body directly.
Upvotes: 2