抓取网络上的图片

不知为啥第二个图片链接必须要打开 setRequestProperty 这行代码才可以获取到图片,第一个图片链接可以不要。

package com.comtop.mop.ueditor.hunter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: 
 * @Date: 2018/11/19 10:26
 * @Description:
 */
public class test1 {
    public static void main(String[] args) {
        String string = "https://images2015.cnblogs.com/blog/844215/201512/844215-20151207132008261-1351288337.png";
//        String string = "http://www.xinhuanet.com/world/2018-11/19/129996753_15425859699771n.jpg";

        try {
            URL url = new URL(string);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
//            connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
//            connection.setInstanceFollowRedirects( true );
//            connection.setUseCaches( true );
            connection.connect();
            InputStream inStream = connection.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte [] buf = new byte[1024];
            int len = 0;
            while((len=inStream.read(buf))!=-1){
                System.out.println(len);
                outStream.write(buf,0,len);
            }
            inStream.close();
            outStream.close();
            File file = new File("F:\\t.jpg");

            FileOutputStream op = new FileOutputStream(file);

            op.write(outStream.toByteArray());

            op.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e){

        }
    }
}

你可能感兴趣的:(Java)