訪問平臺Servlet時,如何設置超時時間

需要的jar包:commons-httpclient-3.1.jar,commons-logging-1.0.4.jar,commons-codec-1.2.jar。在大地財險測試通過。

代碼如下所示:

package cn.com.sinosoft.test.http;

import org.apache.commons.httpclient.HostConfiguration;
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;

public class PostSample {
 public static void main(String[] args) {
  HttpClient httpClient = new HttpClient();
  // 設置代理
  // HostConfiguration hcf = new HostConfiguration();
  // hcf.setProxy("localhost", 8118);
  // httpClient.setHostConfiguration(hcf);

  HttpConnectionManagerParams managerParams = httpClient
    .getHttpConnectionManager().getParams();
  // 設置連接超時時間(單位毫秒)
  managerParams.setConnectionTimeout(30000);
  // 設置讀數據超時時間(單位毫秒)
  managerParams.setSoTimeout(120000);

  String url = "http://localhost/testweb/commserver";
  PostMethod postMethod = new PostMethod(url);

  // 將請求參數XML的值放入postMethod中
  String strResponse = null;
  try {
   postMethod.setRequestEntity(new StringRequestEntity(
     createRequestXML(), "text/xml", "GBK"));
   int statusCode = httpClient.executeMethod(postMethod);
   if (statusCode != HttpStatus.SC_OK) {
    throw new IllegalStateException("Method failed: "
      + postMethod.getStatusLine());
   }
   strResponse = postMethod.getResponseBodyAsString();
  } catch (Exception ex) {
   throw new IllegalStateException(ex.toString());
  } finally {
   // 釋放連接
   postMethod.releaseConnection();
  }
  System.out.println(strResponse);

 }

 public static String createRequestXML() {
  StringBuffer buffer = new StringBuffer();
  buffer.append("<?xml version=/"1.0/" encoding=/"GBK/"?>");
  buffer.append("<PACKET>");
  buffer.append("<HEAD>");
  buffer.append("<REQUEST_TYPE>01</REQUEST_TYPE>");
  buffer.append("</HEAD>");
  buffer.append("</PACKET>");
  return buffer.toString();

 }
}

發佈了60 篇原創文章 · 獲贊 16 · 訪問量 27萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章