需要在 Java 中使用 HttpClient 向後台(Struts2 Action)發送請求,並接收帶參數的字串響應。但 Struts2 預設不允許直接返回字串,需特別處理。
String path = "https://example.com/action";
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(path);
HttpResponse hr = hc.execute(hg);
StatusLine sl = hr.getStatusLine();
if (sl.getStatusCode() == 200) {
HttpEntity he = hr.getEntity();
InputStream is = he.getContent();
// 讀取輸入流轉為字串
String response = IOUtils.toString(is, StandardCharsets.UTF_8);
System.out.println("響應內容: " + response);
}
在 Action 中不直接返回字串,而是通過 HttpServletResponse 寫入:
public void execute() throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write("回傳的參數字串");
}
並在 struts.xml 中將 result 類型設為 stream 或直接在 Action 中處理輸出流。
CloseableHttpClient 與 try-with-resources。