最近写了一个小程序来下载Bing搜索的背景图片,可是出现了一些问题:无论我如何修改,下载下来的始终是,www.bing.com/?mtk=ZN-CN这个网页的背景图片,然而我想下载的是www.bing.com/?mtk=EN-US的背景图片
下面是源码:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReceiveBingPicture {
private static String URL = "";//在网页中的链接
/**
* 获取图片的真实链接
* @param url
* @return
*/
public static String ReceiveUrl(String url) {
String data = "";
BufferedReader in = null;
try {
URL realurl = new URL(url);
HttpURLConnection conntection = (HttpURLConnection) realurl.openConnection();
conntection.connect();
in = new BufferedReader(new InputStreamReader(conntection.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
data += line;
}
String pattern = "/az/hprichbg.*?.jpg";//正则表达式将连接过滤出来
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(data);
m.find();
URL = m.group(0);
System.out.println(URL);
} catch (Exception e) {
e.printStackTrace();
}
return url + URL;
}
/**
* 由真实链接下载图片
* @param urlStr
* @throws IOException
*/
private static void DownloadBingPicture(String urlStr) throws IOException {
URL url = new URL(urlStr);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String fileName = df.format(new Date()) + ".jpg";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println(InetAddress.getLocalHost().getHostAddress());
conn.setConnectTimeout(3 * 1000);
//conn.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
File saveDir = new File("D:/");
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
System.out.println("picture download successs");
}
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
public static void main(String[] args) throws IOException {
DownloadBingPicture(ReceiveUrl("https://www.bing.com/?mtk=EN-US"));
}
}