Description: Java Consume REST API (GET/POST/PUT/DELETE)
Imports
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
URL url = new URL(String);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Sets the general request property. If a property with the key already exists, overwrite its value with the new value.
RequestMethod:
- GET;
- POST;
- PUT;
- DELETE;
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
To enable Output (Request Body) setting: true
conn.setDoOutput(true);
To enable Output (Response Body) setting: true
conn.setDoInput(true);
When a request requires a body (request Body) it is necessary to use OutputStreamWriter to send the data.
OutputStreamWriter output = new OutputStreamWriter(conn.getOutputStream());
output.write(resquestBody.toString());
output.flush();
Gets the status code from an HTTP response message.
conn.getResponseCode()
conn.getResponseMessage()
Output
Status: 200 - OK
When a request receives a body (response Body), it is necessary to use the InputStreamReader to receive the data.
InputStreamReader input = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(input);
String line = null;
StringBuilder responseBody = new StringBuilder();
responseBody.append("responseBody:\n");
while ((line = br.readLine()) != null) {
responseBody.append("\t" + line + "\n");
}
When finished, just disconnect the connection.
conn.disconnect();
Code;
- MalformedURLException
- IOException