天天看點

java類模拟用戶端調用servlet (httpClient)

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.HttpException;

import org.apache.commons.httpclient.HttpStatus;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.params.HttpMethodParams;

......

// 構造HttpClient的執行個體

  HttpClient httpClient = new HttpClient();

  // 建立GET方法的執行個體

  PostMethod postMethod = new PostMethod(url + "servlet/getUrlAddress?");

  // 使用系統提供的預設的恢複政策

  postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,

    new DefaultHttpMethodRetryHandler());

  postMethod.addParameter("username",URLEncoder.encode(username));

  postMethod.addParameter("password",URLEncoder.encode(password));

  try {

   // 執行postMethod

   int statusCode = httpClient.executeMethod(postMethod);

   if (statusCode != HttpStatus.SC_OK) {

    System.err.println("Method failed: " + postMethod.getStatusLine());

   }

   // 讀取内容

   String responseBody = new String(postMethod.getResponseBody());

   // 處理内容

   //System.out.println("servlet傳回的内容 : " + responseBody);

  } catch (HttpException e) {

   // 發生緻命的異常,可能是協定不對或者傳回的内容有問題

   System.out.println("Please check your provided http address!");

   e.printStackTrace();

  } catch (IOException e) {

   // 發生網絡異常

  } finally {

   // 釋放連接配接

   postMethod.releaseConnection();

  }