集册 Java实例教程 从URL加载文件并返回InputStream

从URL加载文件并返回InputStream

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

451
从URL加载文件并返回InputStream
/**
 * N o w  J a v a  . c o m 提 供 
**/


//package com.nowjava;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.ProtocolException;

import java.net.URL;


public class Main {

    public static void main(String[] argv) throws Exception {

        String urlString = "nowjava.com";

        System.out.println(loadFile(urlString));

    }


    public static InputStream loadFile(String urlString) {

        InputStream inuputStream = null;/** 来自 时代Java公众号 - nowjava.com**/

        try {

            URL url = new URL(urlString);


            //create the new connection

            HttpURLConnection urlConnection = (HttpURLConnection) url

                    .openConnection();


            //set up some things on the connection

            urlConnection.setRequestMethod("GET");

            urlConnection.setDoOutput(true);


            //and connect!

            urlConnection.connect();


            //this will be used in reading the data from the internet

            inuputStream = urlConnection.getInputStream();


        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (ProtocolException e) {

            e.printStackTrace();

        } catch (
展开阅读全文