View on GitHub

reading-notes

The HTTP Request Lifecycle

Simple HTTP Request in Java

We can use built-in Java class HttpUrlConnection to to perform basic HTTP requests without the use of any additional libraries.

Creating a Request

Create an HttpUrlConnection instance using the openConnection() method of the URL class

Example:

URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");

Example:

Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");

con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();

Reading the Response

1- int status = con.getResponseCode();

2-

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();

3- con.disconnect();