5

I have a dropwizard service in whitch i implemented a post request who consumes APPLICATION_FORM_URLENCODED media type and uses @FormParam annotation

Then in my client i'm using Apache HttpClient to make a post request like this:

public void sendPost(String path, JsonObject params) throws Exception {

                String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;

                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();

                Iterator<String> keys = params.keySet().iterator();
                while(keys.hasNext()){
                    String currentKey = keys.next();
                    nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
                }
                System.out.println(nvps.toString());
                httpPost.setEntity(new UrlEncodedFormEntity(nvps));

                CloseableHttpResponse response = httpClient.execute(httpPost);

                try {
                    System.out.println(response.getStatusLine());
                    HttpEntity entity2 = response.getEntity();
                    // do something useful with the response body
                    // and ensure it is fully consumed
                    EntityUtils.consume(entity2);
                } finally {
                    response.close();
                }

            }

The url and params I'm passing are correct but i keep getting 400 bad request as a response.

In Postman it works very well...

3
  • There is example for sending url-encoded request: stackoverflow.com/a/59668857/6629515 Commented Jan 9, 2020 at 17:02
  • It seems that there is nothing wrong with this code. Commented Jun 7, 2023 at 10:05
  • URL-encoding (terrible name) is the default for posts. You would have to go to considerable lengths to disable it. 400 doesn't have to mean an encoding problem. You need to look at the server logs. Commented Jun 7, 2023 at 10:43

0

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.