Reputation: 75
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.
Upvotes: 1
Views: 827
Reputation: 9567
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!
Upvotes: 1