HttpClient時著名的開源軟件組織Apache基金會下的一個子項目,它對HTTP協議通信的過程進行了封裝,提供高效且功能豐富的客戶端編程工具包。
package cn.com.cis.claim.car.interf.common.service.facade; public interface HttpClientService { /** * HttpServlet+XML交互發送報文 * chengjie 2017-12-14 * @param strURL * @param requestXML * @return String 返回報文 */ public String postMethod(String strURL, String requestXML); }
package cn.com.cis.claim.car.interf.common.service.spring; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import cn.com.cis.claim.car.interf.common.service.facade.HttpClientService; public class HttpClientServiceSpringImpl implements HttpClientService { public String postMethod(String strURL, String requestXML) { StringBuffer buffer = new StringBuffer(); String strResponse = ""; PostMethod postMethod = null; HttpClient httpClient = new HttpClient(); HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams(); int intCICONNECTTIME = Integer.parseInt("120000"); // 連接超時時間(單位毫秒) int intSoTimeout = Integer.parseInt("180000"); // 連接讀數據超時時間(單位毫秒) managerParams.setConnectionTimeout(intCICONNECTTIME); // 設置連接超時時間(單位毫秒) managerParams.setSoTimeout(intSoTimeout); // 設置讀數據超時時間(單位毫秒)=連接超時時間+1分鍾 System.out.println("********************************"); System.out.println("訪問地址" + strURL); System.out.println("********************************"); BufferedReader reader = null; try { System.out.println("---------->進入try"); System.out.println("strURL-------->" + strURL); postMethod = new PostMethod(strURL); System.out.println("---------->postMethod"); postMethod.setRequestEntity(new StringRequestEntity(requestXML, "text/xml", "GBK")); int statusCode = httpClient.executeMethod(postMethod); System.out.println("statusCode-------->" + statusCode); if (statusCode != HttpStatus.SC_OK) { throw new IllegalStateException("Method failed: " + postMethod.getStatusLine()); } reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream())); System.out.println("reader--------->" + reader); while ((strResponse = reader.readLine()) != null) { buffer.append(strResponse); } } catch (Exception ex) { throw new RuntimeException("發送數據出錯,請聯系管理員!"); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } postMethod.releaseConnection(); } return buffer.toString(); } }
從Servlet中獲取bean
public void init() throws ServletException { claimInfoQueryService = (ClaimInfoQueryService)ServiceFactory.getService(this.getServletContext(),"claimInfoQueryService"); }
