熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

JAVA實現httpClient實例

2022-06-13   來源: Java核心技術 

  /*

  * Created on

  * Copyright by All Rights Reserved

  *

  */

  package netxfokhttp;

  import javautilHashMap; import javautilIterator; import javautilMap;

  import mons; import mons; import mons; import mons; import mons;

  /**

  * @author YangHua

  */

  public class MyClient {

  /**

  *的到Http請求結果

  * @param url請求地址

  * @param parms請求參數

  * @return

  */

  public byte[] getBody(String urlMap parms){

  byte[] body=null;

  //構造HttpClient的實例

  HttpClient httpClient = new HttpClient();

  //創建GET方法的實例

  PostMethod postMethod = new PostMethod(url);

  //填入各個表單域的值

  NameValuePair[] data = new NameValuePair[parmskeySet()size()]; Iterator it = parmsentrySet(erator();

  int i=;

  while (ithasNext()) { MapEntry entry = (MapEntry) itnext(); Object key = entrygetKey(); Object value = entrygetValue(); data[i]=new NameValuePair(keytoString()valuetoString());

  i++;

  }

  //將表單的值放入postMethod中

  postMethodsetRequestBody(data);

  try {

  //執行postMethod

  int statusCode = (postMethod); // HttpClient對於要求接受後繼服務的請求象POST和PUT等不能自動處理轉發

  // 或者

  if (statusCode == HttpStatusSC_MOVED_PERMANENTLY || statusCode == HttpStatusSC_MOVED_TEMPORARILY) {

  //從頭中取出轉向的地址

  Header locationHeader = postMethod

  getResponseHeader(location);

  String location = null;

  if (locationHeader != null) { location = locationHeadergetValue(); Systemout println(The page was redirected to: + location);

  } else {

  Systemerrprintln(Location field value is null);

  }

  }

  body = postMethodgetResponseBody();

  } catch (Exception e) {

  eprintStackTrace();

  }

  return body;

  }

  public static void main(String[] args) {

  String url=;

  Map parms=new HashMap();

  MyClient client=new MyClient();

  String result=new String(clientgetBody(url parms)); Systemoutprintln(result);

  }

  }

  出處


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25989.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.