Read from URLConnection - Java Network

Java examples for Network:URL Download

Description

Read from URLConnection

Demo Code


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URLConnection {

    public static void main(String[] args) throws IOException {
        new URLConnection().doPost();
    }// w w w  .j  a v a  2  s .  c  o  m

    private void doPost() throws IOException {
        String contentType = null;
        URL google = new URL("http://google.co.kr");
        HttpURLConnection conn = (HttpURLConnection) google
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(false);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }

        conn.connect();
        BufferedReader reader = null;
        int rc = conn.getResponseCode();
        InputStream contentStream = null;

        switch (rc) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
            contentStream = conn.getErrorStream();
            break;
        case HttpURLConnection.HTTP_OK:
            contentStream = conn.getInputStream();
            break;
        default:
            throw new IOException("default:" + rc);

        }

        reader = new BufferedReader(new InputStreamReader(contentStream));
        String inputLine = null;
        StringBuffer sb = new StringBuffer();
        while ((inputLine = reader.readLine()) != null) {
            sb.append(inputLine);
        }
        reader.close();
        reader = null;
    }

    private void urlconn2() throws IOException {
        String result = null;
        InputStream is = null;

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        URL google = new URL("http://google.com");
        java.net.URLConnection con = google.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.connect();

        is = con.getInputStream();
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
        result = new String(os.toByteArray());
        System.out.println(result);

    }

    private void urlconn() throws IOException {
        URL google = new URL("http://google.com");
        java.net.URLConnection con = google.openConnection();
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();

    }

}

Related Tutorials