javaandroidapihttpsurlconnection

How to send JSON data to API using HttpsURLConnection on Android?


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


Solution

  • 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!