我使用bing api的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.codec.binary.Base64;
import org.jsoup.Jsoup;
public class bingSearch {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//--------------------------------------Bing search------------------------------
String searchText = "swim";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="Your-AccountKEY";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
// conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
// text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
int find2 = str.indexOf("</d:Description>");
int total2 = find2 + 400;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
char[] buffer2 = new char[1024];
str.getChars(0, find2, buffer2 , 0);
String str2 = new String(buffer2);
str2 = Jsoup.parse(str2).text();
System.out.println(str2);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出结果是:
服务器输出....
Find index: 1014
Total index: 2014
Find index: 1014
Total index: 2014
A computer is a general purpose device that can be programmed to carry out a finite set of arithmetic or logical operations. Since a sequence of operations can be ...
它只显示一个结果,但我需要多个结果。 可以使用此代码吗?或者是其他替代此代码? 谢谢
答案 0 :(得分:1)
在您对Bing的调用中,您要求将结果作为Atom Feed请求,这就是您要回复的内容(该特定查询的长度为38785个字符),您真的应将其视为Atom Feed以更合适的方式解析它。
您只在代码中获得一个结果的原因是您似乎永远不会遍历包含Feed的sb
字符串。如果你真的想以这种方式解析feed,你需要在conn.disconnect()
之后移动到代码循环并使用类似sb.indexOf("<d:Description", int fromIndex)
之类的东西来遍历字符串,每次找到新匹配时都会增加fromIndex。 / p>
但是你真的应该把Bing的响应当作xml-feed来处理它并使用一些xml-library解析它,例如Rome。