HttpClient发送get和post请求

 /**
  * get发送数据请求
  */
 public static void sendClientGet(String url){
  HttpClient client = new HttpClient();
  
  String userName = "sinaweibo4j_cs素颜";
  String userNameUTF = "";
  try {
   userNameUTF = URLEncoder.encode(userName, "UTF-8");
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }
  
  Date date= new Date();  
  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
     String dateFormat=sdf.format(date);
    
     String sign = getMD5String(userName+dateFormat+key);
    
  
  
  String urlStr = url+"?username="+userNameUTF;

  Log.logInfo(urlStr);
  
  GetMethod method = new GetMethod(urlStr);
  method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
  //使用POST方法
  //HttpMethod method = new PostMethod("http://localhost:8888/abc/a.jsp");
  try {
   client.executeMethod(method);
   Log.logInfo(method.getStatusLine().toString());
   //打印返回的信息
   Log.logInfo("返回信息:"+method.getResponseBodyAsString());
  } catch (HttpException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  //打印服务器返回的状态
  
  //释放连接
  method.releaseConnection();

 }
 
 /**
  * post发送数据请求 
  * @param url
  * @param param
  * @return
  */
 public static boolean sendClientPost(String url,NameValuePair[] param){

  HttpClient httpClient = new HttpClient(); 
  PostMethod postMethod = new PostMethod(url); 
  
  postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");
  //postMethod.setRequestHeader("ContentType",
  //"application/x-www-form-urlencoded;charset=UTF-8");
  //postMethod.setRequestBody(param);
  
  postMethod.setFollowRedirects(false);
  postMethod.addParameters(param);
  StringBuffer resultBuffer = new StringBuffer();
  try {
   httpClient.executeMethod(postMethod);
   
   BufferedReader in = new BufferedReader(
     new InputStreamReader(postMethod.getResponseBodyAsStream(),postMethod.getResponseCharSet()));
   Log.logInfo("-------------PostMethod:"+postMethod.getResponseBodyAsStream());
   
   String inputLine = null;
   while ((inputLine = in.readLine()) != null) {
    //inputLine = ConverterStringCode(inputLine,method.getResponseCharSet(),"gb2312");
    resultBuffer.append(inputLine);
    resultBuffer.append("\n");
   }
   in.close();
   
   Log.logInfo("-------------resultBuffer:"+resultBuffer.toString());
   
   return true;
   
  } catch (HttpException e) {
   
   Log.logInfo("-------------httpException:"+e);
   e.printStackTrace();
  } catch (IOException e) {
   
   Log.logInfo("-------------IOException:"+e);
   e.printStackTrace();
  }
  
  return false;
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值