HTTP接口编程 GET方式

本文介绍如何使用 HTTPClient 实现 GET 请求,并提供了一个示例代码。文章对比了使用 URLConnection 和 HTTPClient 的区别,强调了正确设置请求参数的重要性。

HTTP 接口 一般比较常用的 类 有HTTPClient,及URLConnection,GET方式发送报文只能设置包头 然后将要发送的报文放入 要访问的URL中,如果用URLConnection的方式去发送报文,即便是在 URLConection中设置httpUrlConnection.setRequestMethod("GET"); 时.若在中写入 httpUrlConnection.getOutputStream().writeObject(new String("我是测试数据"));非URL之外的码流时,用抓包工具分析时会自动转化为POST方式,所以用URLConnection用GET方式发送报文不靠谱.所以 要用HTTP接口GET方式最好使用HTTPClient方式.

  1. public   static  String getDoGetURL(String url, String charset) throws  Exception {   
  2.   
  3.         HttpClient client =  new  HttpClient();   
  4.         GetMethod method1 =  new  GetMethod(url);   
  5.   
  6.          if  ( null  == url || !url.startsWith( "http" )) {   
  7.              throw   new  Exception( "请求地址格式不对" );   
  8.         }   
  9.   
  10.          // 设置请求的编码方式   
  11.          if  ( null  != charset) {   
  12.             method1.addRequestHeader( "Content-Type" ,   
  13.                      "application/x-www-form-urlencoded; charset="  + charset);   
  14.         }  else  {   
  15.             method1.addRequestHeader( "Content-Type" ,   
  16.                      "application/x-www-form-urlencoded; charset="  +  "utf-8" );   
  17.         }   
  18.          int  statusCode = client.executeMethod(method1);   
  19.   
  20.          if  (statusCode != HttpStatus.SC_OK) { // 打印服务器返回的状态   
  21.             System.out.println( "Method failed: "  + method1.getStatusLine());   
  22.         }   
  23.          // 返回响应消息   
  24.          byte[] responseBody = method1.getResponseBodyAsString().getBytes(method1.getResponseCharSet());   
  25.          // 在返回响应消息使用编码(utf-8或gb2312)   
  26.         String response =  new  String(responseBody,  "utf-8" );   
  27.         System.out.println( "------------------response:" +response);   
  28.          // 释放连接   
  29.         method1.releaseConnection();   
  30.          return  response;   
  31.     }   
 这个示例 是一个比较标准的   用HTTPClient 做的get方式.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值