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

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

My api returns a JSON object, can I use that way to read the answer to treat the JSON object?, thank you
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.

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.