1

I'm using Apache HttpClient to send sms via my project, I have this function:

  public void sendSMS(SMS sms) throws IOException {
    String auth = smsUsername + ":" + smsPassword;
    byte[] encodedAuth = encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
    
    ObjectMapper oMapper = new ObjectMapper();    
    Map<String, Object> map = oMapper.convertValue(sms, Map.class);
    StringEntity params = new StringEntity(map.toString());       

    HttpPost post = new HttpPost(smsEndpoint);
    post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(encodedAuth));   
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    post.setEntity(params);       
    
    try (CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(post)) {
        LOGGER.log(Level.INFO, () -> "the response: " + response.toString());
    }
}

My problem is the parameters into the url are empty, how do I resolve that? Thanks in advance.

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78
slema imen
  • 75
  • 1
  • 10
  • `smsEndpoint` contains your end-point URL and has not been modified in your code (code adds headers and entity). What parameters do you want to send as a part of the URL? – Vini Dec 15 '22 at 08:55
  • sms is a request body that not been send into the url – slema imen Dec 15 '22 at 08:59
  • For POST, the values are sent in the request body and not in the URL. Are you trying to get the 'params' on the sever side? You will get that in the request body. – Vini Dec 15 '22 at 09:16
  • This question explains the difference on how the data is sent in a POST request in great detail - https://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request – Vini Dec 15 '22 at 09:39

1 Answers1

1

Adding an entity to a HttpPost will add a body. If you want to add parameters, you have to add it to the url. At the moment your URL is the smsEndpoint.

You can just add the parameters there:

List<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("param1", "value1"));

HttpPost httpPost = new HttpPost(smsEndpoint);
URI uri = new URIBuilder(httpPost.getURI())
            .addParameters(nameValuePairs)
            .build();
httpPost.setURI(uri);

See also: https://www.baeldung.com/apache-httpclient-parameters!

Jacob van Lingen
  • 8,989
  • 7
  • 48
  • 78