Pythalex
12/9/2018 - 3:24 PM

Java - Http request

"Low" level HTTP request with java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Request {

    public static void main(String[] args) throws IOException {
        // Initialize connexion
        URL url = new URL("https://example.com");
        HttpURLConnection cnx = (HttpURLConnection) url.openConnection();
        cnx.setRequestMethod("GET");

        // declare headers with setRequestProperty
        cnx.setRequestProperty("Content-type", "application/json");

        // Add parameters to the request
        /**
         * Parameters will be sent with the form param1=val1&param2=val2
         */
        Map<String, String> parameters = new HashMap<>();
        parameters.put("param1", "val1");
        parameters.put("param2", "val2");
        parameters.put("param3", "val3");

        // use the connexion for output
        cnx.setDoOutput(true);

        // Create an output stream from connexion and send informations
        DataOutputStream out = new DataOutputStream(cnx.getOutputStream());

        StringBuilder sb = new StringBuilder();
        for(String key: parameters.keySet())
            sb.append(key + "=" + parameters.get(key) + "&");

        out.writeBytes(sb.toString());
        out.flush();
        out.close();

        // Read the response
        BufferedReader in = new BufferedReader(new InputStreamReader(cnx.getInputStream()));

        String line;
        sb.delete(0, sb.length()); // reset builder
        while ((line = in.readLine()) != null){
            sb.append(line);
            sb.append("\n");
        }

        in.close();

        // Now you have the response
        System.out.println(sb.toString());

        // end the connexion
        cnx.disconnect();
    }

}