0

I am trying to send request from Java to Twilio SMS API. I am using java.net.http package:

var url = UriBuilder.fromUri(
                "https://api.twilio.com/2010-04-01/Accounts/MyAccount/Messages.json").build();

var urlEncodedBody = URLEncoder.encode(String.format("To=%s&From=%s&Body=%s",
                                                         "+1123456789",
                                                         "+1223456789",
                                                         "Hello"),
                                           StandardCharsets.UTF_8);
var request = HttpRequest.newBuilder(url)
                             .headers("Authorization", "Basic " + base64,
                                      "Content-Type", "application/x-www-form-urlencoded")
                             .method("POST", HttpRequest.BodyPublishers.ofString(
                                     urlEncodedBody))
                             .build();

HttpClient httpClient = HttpClient.newBuilder().build();

try {
            var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException |
                InterruptedException e) {
            throw new RuntimeException(e);
}

I keep getting the error response:

{"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400}

Any idea what I'm missing?

CuriousGuy
  • 1,545
  • 3
  • 20
  • 42

1 Answers1

3

I think when you encode the body of the request you are also encoding the &s and =s so it just seems to be one string.

This answer on a different question suggests using a Map and encoding each value in turn. Using that as a basis, your could replace your string formatting with:

Map<String, String> parameters = new HashMap<>();
parameters.put("To", "+1123456789");
parameters.put("From", "+1223456789");
parameters.put("Body", "Hello");

String urlEncodedBody = parameters.entrySet()
    .stream()
    .map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
    .collect(Collectors.joining("&"));
philnash
  • 70,667
  • 10
  • 60
  • 88