1

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?

2
  • 1
    Consider using Jersey: jersey.java.net Commented Oct 10, 2014 at 20:32
  • I know little about HttpClient/HttpPost, but do they send the data as a JSON string? Don't you have to set the content type in the header either? Commented Oct 10, 2014 at 21:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.