使用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(); } } }
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/14008.html