Code example for HttpURLConnection

Methods: setRequestMethodaddRequestPropertygetOutputStreamsetDoOutputsetRequestProperty

0
    } 
 
    public static URLConnection httpPostCompressed(WebServer webServer, String path, String body) throws IOException {
        URL url = new URL(webServer.getUri().toURL(), path);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("Content-Encoding", "gzip");
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        urlConnection.setDoOutput(true);
 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(baos);
        gzip.write(body.getBytes(Charset.forName("UTF8")));
        gzip.close();
 
        urlConnection.getOutputStream().write(baos.toByteArray());
        return urlConnection;
    } 
 
    public static String contents(URLConnection urlConnection) throws IOException {
        int length = urlConnection.getContentLength();