首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

使用 HttpClient 發送請求並接收帶參數的響應實作指南

     編輯:程式設計綜合問答

需求背景

需要在 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); 
}

Struts2 端配合處理

在 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 中處理輸出流。

注意事項

  • 確保關閉資源(HttpClient、InputStream)避免洩漏。
  • HttpClient 4.3+ 建議使用 CloseableHttpClient 與 try-with-resources。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved