执行HTTP

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

397
执行一个HTTP-GET请求,并将答案的内容本地存储到一个文件中
/** 来自 时代Java**/


//package com.nowjava;

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.URL;


public class Main {

    /**

     * Executes an HTTP-GET request and stores locally down to a file the content of the answer

     * @param url the URL to post a GET to

     * @param fileName the filename to store the result of the GET request locally

     * @return true if the file was successfully created

     * @throws Exception

     */

    public static boolean getUrl(String url, String fileName)

            throws Exception {

        boolean succes = false;

        URL urlObj = new URL(url);

        InputStream inputStream = urlObj.openStream();/** from N o w J a v a . c o m - 时代Java**/

        BufferedReader in = new BufferedReader(new InputStreamReader(

                inputStream, "UTF8"));

        BufferedWriter sortie = new BufferedWriter(new OutputStreamWriter(

                new FileOutputStream(fileName), "UTF-8"));


        String inputLine;

        String contenu = "";


        while ((inputLine = in.readLine()) != null)

            contenu += inputLine + "\n";


        sortie.write(contenu);

        sortie.close();


   
展开阅读全文