网络图片下载(带请求头)

    String url="https://xxxx";
		InputStream ism = null;
		File dir = new File("F:/downloads/test.jpg");//下载路径
		try{
			System.out.println(url);
			URL imgUrl = new URL(url);
			HttpURLConnection conn=(HttpURLConnection)imgUrl.openConnection();
			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Mobile Safari/537.36");
			
			ism = conn.getInputStream();
			if(ism!=null){
				OutputStream osm = new FileOutputStream(dir);
				byte[] buff = new byte[1024];
				while (true) {
					int readed = ism.read(buff);
					if (readed == -1) {
						break;
					}
					byte[] temp = new byte[readed];
					System.arraycopy(buff, 0, temp, 0, readed);
					osm.write(temp);
				}
				osm.close();
			}
		}catch(Exception e){
			e.printStackTrace();
		}

猜你喜欢

转载自blog.csdn.net/GrassEva/article/details/80404207