IT虾米网

Java获取get请求图片资源详解

xmjava 2018年08月17日 编程语言 144 0

使用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(); 
	        } 
	    }  
} 



发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

HashMap与ConcurrentHashMap的区别详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。