SUN认证

JAVA实现httpClient的实例

时间:2024-11-05 11:03:45 SUN认证 我要投稿
  • 相关推荐

关于JAVA实现httpClient的实例

  HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。下面小编准备了关于JAVA实现httpClient的实例,提供给大家参考!

  package net.xfok.http;

  import java.util.HashMap; import java.util.Iterator; import java.util.Map;

  import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod;

  /**

  */

  public class MyClient {

  /**

  *的到Http请求结果

  * @param url请求地址

  * @param parms请求参数

  * @return

  */

  public byte[] getBody(String url,Map parms){

  byte[] body=null;

  //构造HttpClient的实例

  HttpClient httpClient = new HttpClient();

  //创建GET方法的实例

  PostMethod postMethod = new PostMethod(url);

  //填入各个表单域的值

  NameValuePair[] data = new NameValuePair[parms.keySet().size()]; Iterator it = parms.entrySet().iterator();

  int i=0;

  while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); data[i]=new NameValuePair(key.toString(),value.toString());

  i++;

  }

  //将表单的值放入postMethod中

  postMethod.setRequestBody(data);

  try {

  //执行postMethod

  int statusCode = httpClient.executeMethod(postMethod); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发

  // 301或者302

  if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {

  //从头中取出转向的地址

  Header locationHeader = postMethod

  .getResponseHeader(“location”);

  String location = null;

  if (locationHeader != null) { location = locationHeader.getValue(); System.out .println(“The page was redirected to:” + location);

  } else {

  System.err.println(“Location field value is null.”);

  }

  }

  body = postMethod.getResponseBody();

  } catch (Exception e) {

  e.printStackTrace();

  }

  return body;

  }

  public static void main(String[] args) {

  String url=“http://www.xfok.net”;

  Map parms=new HashMap();

  MyClient client=new MyClient();

  String result=new String(client.getBody(url, parms)); System.out.println(result);

  }

  }

【JAVA实现httpClient的实例】相关文章:

PHP实现RSA加密类的实例解析08-24

使用JavaScript实现Java的List功能08-09

Javascript简单实现面向对象编程继承实例代码10-14

java实现web服务器的方法09-26

jQuery实现的拖动调整表格单元格的大小代码实例08-27

关于jQuery实现页面顶部显示的进度条效果完整实例09-16

JavaScript实例讲解08-29

Java与Java web的区别08-22

photoshop实例教程07-08

新托福口语实例09-29