เขียนโปรแกรม Download Image จาก http

วันนี้มาลองเขียนโปรแกรมเพื่อ save image จาก website ซึ่งผ่าน http กันดู เผื่อจะได้เอาไปต่อยอดทำอย่างอื่นต่อไป

library ที่ใช้ apache http component

package mangaloader;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
/**
 *
 * @author kajookdecv
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        //if have proxy
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("proxyHost", 8080),
                new UsernamePasswordCredentials("username", "password"));
        HttpHost proxy = new HttpHost("proxyHost",8080);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        
        //save image from
        HttpUriRequest req = new HttpGet("http://cdn04.eboy.in.th/manga/cuhafivfdai/wqerdvipo/TH/gantz/TH/323/001.inc.dll");
        HttpResponse httpResponse = httpclient.execute(req);
        HttpEntity entity = httpResponse.getEntity();
        //Write to
        FileOutputStream fos = new FileOutputStream(new File("d:/temp/test.jpg"));
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        if(entity.isStreaming()){
            entity.writeTo(bos);
        }else {
            System.out.println("not streaming.");
        }
        bos.close();
        fos.close();

    }

}

About WK

Kajook is a Senior Software Engineer. Job is Design & Develop in Java EE environment on Glassfish. I'm Interested in Agile software development ,iOS and Android.
This entry was posted in knowledge and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s