request And Write Resources From Http Server - Android Network

Android examples for Network:HTTP Request

Description

request And Write Resources From Http Server

Demo Code


//package com.java2s;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static String requestAndWriteResourcesFromServer(String httpUrl,
            String localFile) {//  w  ww .j a v  a2 s .  co  m
        BufferedReader reader = null;
        BufferedWriter writer = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            writer = new BufferedWriter(new FileWriter(localFile));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                writer.write(strRead);
                sbf.append("\r\n");
            }
            writer.flush();
            reader.close();
            writer.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

Related Tutorials