Getting HTTP 406 while calling external site from within servlet

Werner van Mook picture Werner van Mook · May 19, 2011 · Viewed 8.2k times · Source

I have the following code in my servlet:

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
public void doIt(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    URL url = new URL("http://some.url.that.works.well.nl/q=hello&ie=nl&cx=hdyehgfyegywjehdkwed:7364du7");

    URLConnection conn = url.openConnection();
    conn.connect();

    BufferedReader br = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));  // This line is generating the error
    String line = "";
    PrintWriter pw = response.getWriter();
    while((line = br.readLine()) != null) {
        pw.println(line);
    } 
}

running this servlet in tomcat gives me an http 406 error.

What I try to do is from within my servlet call google site search and I would like to parse the receieved (XML) result. (For now I just print te received result). Trying the url in a browser is giving the correct result.

What am I missing here?

Kind regards, Werner

Answer

Vivien Barousse picture Vivien Barousse · May 19, 2011

A 406 HTTP error means that the server couldn't build a response to your request with an acceptable content type. It means that your URLConnection asks the server for a given content type, and the server can't find an appropriate one.

You can change the content type requested by your URLConnection using the setRequestProperty(String, String) method. You will have to add something like:

conn.setRequestProperty("accept", "text/xml");

(This supposes the server sends XML back to you)