-
Notifications
You must be signed in to change notification settings - Fork 6
/
BingSearch.java
36 lines (30 loc) · 1.3 KB
/
BingSearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.markwatson.search;
import org.apache.commons.codec.binary.Base64;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* author: Mark Watson
*/
public class BingSearch {
//https://api.datamarket.azure.com/Bing/Search/Web?Query=%27Xbox%27&Options=%27DisableLocationDetection%2BEnableHighlighting%27
public static String search(String query) throws Exception {
String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?Query=%27" + java.net.URLEncoder.encode(query) + "%27&$format=JSON";
String accountKey = System.getenv("BING_API_KEY");
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); // code for encoding found on stackoverflow
String accountKeyEnc = new String(accountKeyBytes);
URL url = new URL(bingUrl);
URLConnection urlConnection = url.openConnection();
String s1 = "Basic " + accountKeyEnc;
urlConnection.setRequestProperty("Authorization", s1);
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
StringBuffer sb = new StringBuffer();
while ((inputLine = in.readLine()) != null)
sb.append(inputLine);
in.close();
return sb.toString();
}
}