2

How can I send JSON data using HttpsURLConnection to my API ?, this is my code

 URL endpoint = new URL("https://api.url.com/api/token/");

  // Create connection
     HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
     myConnection.setRequestMethod("POST");
     myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
     myConnection.setRequestProperty("Accept", "application/json");
  // Create the data
     String myData = "{\"username\":\"username\",\"password\":\"password\"}";

  // Enable writing
     myConnection.setDoOutput(true);

  // Write the data
     myConnection.getOutputStream().write(myData.getBytes());

     if (myConnection.getResponseCode() == 200) {
         InputStream responseBody = myConnection.getInputStream();
         InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
         JsonReader jsonReader = new JsonReader(responseBodyReader);}
}

I tried this way, but it doesn't work.

Thank you

Alex Onofre
  • 345
  • 1
  • 3
  • 17

1 Answers1

1

Send the request:

String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);

try(OutputStream outputStream = conn.getOutputStream()) {
    byte[] input = myData.getBytes("utf-8");
    outputStream.write(input, 0, input.length);           
}

To read the response:

StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line.trim());
    }
}
System.out.println(sb.toString());

I hope that helps!

djharten
  • 374
  • 1
  • 12
  • My api returns a JSON object, can I use that way to read the answer to treat the JSON object?, thank you – Alex Onofre Jan 31 '20 at 15:02
  • Your API should return JSON data. You can turn it into a JSON object in Java. Look at the faster jackson library. There are some good introductions to it [here](https://mkyong.com/java/jackson-2-convert-java-object-to-from-json/). – djharten Jan 31 '20 at 15:06