How to Implement GET and POST Requests With Java

How to Implement GET and POST Requests With Java

To send an HTTP GET request using Java, you can use the HttpURLConnection class provided in the java.net package. Here is an example of how you can use this class to send a GET request and print the response:

refer to:‮tual‬turi.com
import java.io.*;
import java.net.*;

public class HttpGetExample {

    public static void main(String[] args) throws IOException {
        // Create a URL object for the desired page
        URL url = new URL("http://www.example.com");

        // Open a connection to the URL
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Set the request method to GET
        conn.setRequestMethod("GET");

        // Read the response from the server
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        // Close the connection
        in.close();
    }
}

To send an HTTP POST request using Java, you can use the HttpURLConnection class in a similar way. Here is an example of how you can use this class to send a POST request with a JSON payload and print the response:

import java.io.*;
import java.net.*;

public class HttpPostExample {

    public static void main(String[] args) throws IOException {
        // Create a URL object for the desired page
        URL url = new URL("http://www.example.com");

        // Open a connection to the URL
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Set the request method to POST
        conn.setRequestMethod("POST");

        // Set the request content type to JSON
        conn.setRequestProperty("Content-Type", "application/json");

        // Set the request body
        String payload = "{\"key\":\"value\"}";
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(payload);
        out.close();

        // Read the response from the server
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        // Close the connection
        in.close();
    }
}

Note that this example uses the HttpURLConnection class, which is part of the standard Java library. If you want to use a more advanced HTTP client library with additional features, you might consider using a library like Apache HttpClient or OkHttp.

Created Time:2017-11-01 20:42:47  Author:lautturi