I'm trying to use the google custom search using a restful client . I basically followed this link . My code is below
public class GoogleCrawler {
final static String apiKey = "key";
final static String customSearchEngineKey = "CX value";
final static String searchURL = "https://www.googleapis.com/customsearch/v1?";
private static String makeSearchString(String qSearch,int start,int numOfResults)
{
String toSearch = searchURL + "key=" + apiKey + "&cx=" + customSearchEngineKey+"&q=";
//replace spaces in the search query with +
String keys[]=qSearch.split("[ ]+");
for(String key:keys)
{
toSearch += key +"+"; //append the keywords to the url
}
//specify response format as json
toSearch+="&alt=json";
//specify starting result number
toSearch+="&start="+start;
//specify the number of results you need from the starting position
toSearch+="&num="+numOfResults;
return toSearch;
}
private static String read(String pUrl)
{
//pUrl is the URL we created in previous step
try
{
URL url=new URL(pUrl);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer buffer=new StringBuffer();
while((line=br.readLine())!=null){
buffer.append(line);
}
return buffer.toString();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
public static void main (String[] args)
{
String toSearch=makeSearchString("katrina",1,100);
System.out.println(read(toSearch));
}
}
And I'm getting a bad request HTTP 400 from the server.
java.io.IOException: Server returned HTTP response code: 400 for URL: https://www.googleapis.com/customsearch/v1?key=key&cx=cx&q=katrina+&alt=json&start=1&num=100
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.main.GoogleCrawler.read(GoogleCrawler.java:45)
at com.main.GoogleCrawler.main(GoogleCrawler.java:62)
Any idea on what Im doing wrong would be appreciated