Java獲取get請求圖片資源

使用Apache的HttpClient包

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpTest {
	 public static void main(String[] args) throws ClientProtocolException, IOException  
	    {  
		 	CloseableHttpClient httpclient = HttpClients.createDefault(); 
	        try {
	            HttpGet httpGet = new HttpGet("http://img2.126.net/xoimages/8/20141101/x/640x100.jpg");
	            CloseableHttpResponse response = httpclient.execute(httpGet);
	            try {
	                HttpEntity entity = response.getEntity();
	                InputStream inStream = entity.getContent();
	                FileOutputStream fw = new FileOutputStream("C:/Users/MIAO/Desktop/Response.jpg", false);
	    			int b = inStream.read();
	    			while (b != -1) {
	    				fw.write(b);
	    				b = inStream.read();
	    			}
	                fw.close();
	                EntityUtils.consume(entity);
	            } finally {
	                response.close();
	            }
	        }finally {
	            httpclient.close();
	        }
	    } 
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章