I am using eclipse ganymede and trying to create a servlet which takes a query from the user and outputs the google search results of that query. I would like to parse the response which I get from google but at the moment, I am not even able to get the response.
I know this might be because of the way Google accept requests, so is there any way I can achieve this. I would like to avoid using the Google Custom Search API, as it has it's own complications, but if there is no other way, please let me know.
EDIT: Bing Search is working after setting up proxy but no luck with Google search, is it because of https?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// reading the user input
String query = request.getParameter("query");
PrintWriter out = response.getWriter();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.address", 8080));
URL urldemo = new URL("https://www.google.co.in/search?q="+query);
//urldemo = new URL("http://www.bing.com/search?q="+query);
URLConnection yc = urldemo.openConnection(proxy);
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
System.out.println(inputLine);
}
in.close();
}
}
Stack Trace:
java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.co.in/search?q=easd
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
HelloWorld.doGet(HelloWorld.java:30)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)