简体   繁体   中英

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM