Java code to retrieve Bing background image path
Summary
A Java code example demonstrates a method for programmatically retrieving the daily background image URL from Bing's homepage. The approach involves establishing an HTTP connection to www.bing.com and reading its HTML source code line by line. Within the retrieved HTML, the Java code parses the content using string manipulation to locate and extract the image's relative path. This path is then combined with the base URL to form the complete image link, offering a simple technique for developers to access specific dynamic web content.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class BingBGImagePathRetriever {
public static void main(String[] args) {
String imgSrc="";
try {
URL htmlUrl = new URL("http://www.bing.com");
URLConnection htmlConn = htmlUrl.openConnection();
htmlConn.connect();
HttpURLConnection htmlHttpConn = (HttpURLConnection) htmlConn;
if ((int) htmlHttpConn.getResponseCode() != 200) {
System.out.println("Cannot open connection.");
} else {
BufferedReader reader = new BufferedReader(
new InputStreamReader(htmlConn.getInputStream()));
String str = "";
while ((str = reader.readLine()) != null) {
if (str.lastIndexOf("{url:") > 0) {
imgSrc = str.substring((str.lastIndexOf("{url:") + 7),
(str.lastIndexOf(".jpg',") + 4));
}
}
imgSrc = "http://www.bing.com" + imgSrc; // The source image url from Bing search engine.
System.out.println(imgSrc);
}
} catch (Exception ioEx) {
ioEx.printStackTrace();
}
}
}
The code is quite simple, basically what it does is first it retrieve the source code of the home page of Bing and then it parse the source code and find the position of background image path, then use some string functions to build the complete path string.
No comment for this article.