httpClient.execute中的ClientProtocolException(httpget,responseHandler)

我使用以下代码从Web服务器请求xml:

HttpClient httpclient = new DefaultHttpClient() try { HttpGet httpget = new HttpGet("http://63.255.173.242/get_public_tbl.cgi?A=1"); ResponseHandler responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } 

当我调用httpclient.execute(httpget,responseHandler)时,我得到一个clientProtocolException。 url在Web浏览器中工作正常,它返回xml,浏览器显示它。

任何想法为什么我会得到一个clientProtocolException但浏览器处理它就好了?

编辑1:

查看协议exception,详细消息是:“服务器无法响应有效的HTTP响应”。 我无法更改我正在访问的Web服务器。 有没有办法忽略这个并只是访问响应?

编辑2:

我发现服务器没有发回完整的标头。 有没有办法访问响应的内容,即使返回一个损坏的标题?

编辑3:我编辑的IP地址是我正在打的真实IP地址。 任何帮助将非常感激。

由于您的代码似乎是正确的,您必须弄清楚:这是客户端的错误(无效请求),还是服务器的错误(无效响应)。 为此,请使用http trace utitlity并将浏览器的请求与客户端的请求进行比较。 如果有的话,您还可以看到服务器的原始响应。 如果您无法弄明白,请将原始请求和响应添加到您的问题中,然后某人可能会提供帮助。

我用我的IP地址测试了你的代码。 代码中没有错误。 我刚刚将ResponseHandler更改为BasicResponseHandler

检查一下

  HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("http://www.MyServer.com/get_public_tbl.cgi?A=1"); BasicResponseHandler responseHandler = new BasicResponseHandler();//Here is the change String responseBody = httpclient.execute(httpget, responseHandler); System.out.println(responseBody); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } 

您可以尝试添加自己的响应拦截器,您可以在其中添加或删除标头,或打印一些调试信息

 hc.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { response.getEntity().writeTo(System.out); } }); 

检查您在客户端中设置的标题,重新validation标题的键和值。 在我的情况下,我使用“csrf”param而不是“Cookie”。