集册 Java实例教程 从URLConnection读取

从URLConnection读取

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
从URLConnection读取


import java.io.BufferedReader;
/*
时代Java公众号 - N o w J a  v a . c o m 提供
*/

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 {/** 来自 时代Java - N o w  J a v a . c o m**/

        new URLConnection().doPost();

    }


    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);


    }


    
展开阅读全文