如何从HTTPClient调用的Servlet获取对HTTPClient的响应?

时间:2012-01-08 07:57:49

标签: java

我能够使用HttpClient成功发布到servlet。但是我需要从servlet返回HttpClient的布尔参数,我不知道如何做同样的事情。

Earleir我使用的是common-httpclient-3.1.jar.However然后我知道httpclient的版本升级到4.0,这有助于HttpResponse的响应处理。现在我使用的是httpclient.4.0.3,httpcore-4.1和httpmime-4.1.1。我尝试的代码如下HttpClient。

HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("http://localhost:9090/drools-guvnor/KeystoneServlet");
HttpEntity entity = method.getEntity();
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("directory", directory));
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("password", password));
method.setEntity(new UrlEncodedFormEntity(nvps));
ResponseHandler responseHandler = new BasicResponseHandler();
HttpResponse response = client.execute(method, responseHandler);
System.out.println("responseBody: "+responseHandler.handleResponse(response));

在KeyStoneServlet中,我能够成功获取参数目录,用户名和密码。进一步使用这些参数我正在进行进一步处理,并且能够检索我想要作为对HttpClient的响应的布尔参数。但是我不知道我怎么能这样做。上面的responseBody SOP是空白的,并没有向我显示任何内容。

对此相关的任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

有许多方法可以从servlet返回数据.. JSON,XML,纯文本。您所要做的就是:

response.setContentType("text/xml");
PrintWriter pw=response.getWriter();
pw.write(<reponse data string xml>);

接收httpclient上的数据并解析它。如果您需要的只是布尔值,那么单个字符串表示true / false应该这样做。但是如果您想从servlet中抛出异常怎么办?在这种情况下,XML更健壮。

如果不想解析xml或文本并处理响应,请尝试使用Web服务..

编辑:回复评论:

在您的servlet中,您可以访问HTTPResponse对象。让我们使用响应来表示这个对象。

response.setContentType("text/plain");
PrintWriter pw=response.getWriter();
pw.write(<true or false based on your processing>);

现在在您的客户端代码中,我没有使用httpclient 4 ...所以这是使用httpclient 3 -

HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("http://localhost:9090/drools-guvnor/KeystoneServlet");
HttpEntity entity = method.getEntity();
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("directory", directory));
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("password", password));
method.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse httpResponse = client.execute(method);
int statusCode = httpResponse.getStatusLine().getStatusCode(); 
if (statusCode == HttpStatus.SC_OK) {
    InputStream is = httpResponse.getEntity().getContent();

    //convert your stream into a string and convert it into a boolean
}

对不起我没有httpclient 4来检查..但我相信上面应该有效..

我不建议发回纯文本。而是使用XML并以与上面相同的方式处理它。