簡體   English   中英

如何從HTTPClient調用的Servlet獲取對HTTPClient的響應?

[英]How to get a response to HTTPClient from a Servlet which is called from the HTTPClient?

我能夠使用HttpClient成功發布到servlet。 但是我需要一個從servlet返回到HttpClient的布爾參數,並且不確定如何執行相同的操作。

Earleir我當時使用的是common-httpclient-3.1.jar。但是后來我意識到將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空白,沒有顯示任何內容。

對此的任何協助將不勝感激。

有很多方法可以從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並以與上述相同的方式處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM