java 模拟http请求获取数据

时间:2022-08-10 16:57:56
  1. 引入commons-httpclient-3.1.jar

  1. public static void main(String[] args) {
HttpClient client = new HttpClient(); 
PostMethod method = new PostMethod(待请求的url地址);   

method.addParameter("参数名", 参数值);
method.addParameter("参数名", 参数值);

        HttpMethodParams param = method.getParams();  
        param.setContentCharset("UTF-8");  
       
        StringBuffer buf = new StringBuffer();  
   try 
   {
client.executeMethod(method);

   InputStream stream = method.getResponseBodyAsStream();  
      
   BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));  
   String line;  
    
   while (null != (line = br.readLine())) 
   {  
       buf.append(line).append("\n");  
   }  


   //释放连接  
   method.releaseConnection();  

} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

   
   String result = buf.toString();
   
   System.out.println(result);


}