Java模拟HTTP的Get和Post请求

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
简介:
借助Apache Commons-httpclient的力量,轻松实现了对HTTP请求的模拟!
 
下面是一个测试代码:
import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.HttpMethod; 
import org.apache.commons.httpclient.HttpStatus; 
import org.apache.commons.httpclient.URIException; 
import org.apache.commons.httpclient.methods.GetMethod; 
import org.apache.commons.httpclient.methods.PostMethod; 
import org.apache.commons.httpclient.params.HttpMethodParams; 
import org.apache.commons.httpclient.util.URIUtil; 
import org.apache.commons.lang.StringUtils; 
import org.apache.commons.logging.Log; 
import org.apache.commons.logging.LogFactory; 

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

/** 
* HTTP工具箱 

* @author leizhimin 2009-6-19 16:36:18 
*/
 
public  final  class HttpTookit { 
         private  static Log log = LogFactory.getLog(HttpTookit. class); 

         /** 
         * 执行一个HTTP GET请求,返回请求响应的HTML 
         * 
         * @param url                 请求的URL地址 
         * @param queryString 请求的查询参数,可以为null 
         * @return 返回请求响应的HTML 
         */
 
         public  static String doGet(String url, String queryString) { 
                String response =  null
                HttpClient client =  new HttpClient(); 
                HttpMethod method =  new GetMethod(url); 
                 try { 
                         if (StringUtils.isNotBlank(queryString)) 
                                method.setQueryString(URIUtil.encodeQuery(queryString)); 
                        client.executeMethod(method); 
                         if (method.getStatusCode() == HttpStatus.SC_OK) { 
                                response = method.getResponseBodyAsString(); 
                        } 
                }  catch (URIException e) { 
                        log.error( "执行HTTP Get请求时,编码查询字符串“" + queryString +  "”发生异常!", e); 
                }  catch (IOException e) { 
                        log.error( "执行HTTP Get请求" + url +  "时,发生异常!", e); 
                }  finally { 
                        method.releaseConnection(); 
                } 
                 return response; 
        } 

         /** 
         * 执行一个HTTP POST请求,返回请求响应的HTML 
         * 
         * @param url        请求的URL地址 
         * @param params 请求的查询参数,可以为null 
         * @return 返回请求响应的HTML 
         */
 
         public  static String doPost(String url, Map<String, String> params) { 
                String response =  null
                HttpClient client =  new HttpClient(); 
                HttpMethod method =  new PostMethod(url); 
                 for (Iterator it = params.entrySet().iterator(); it.hasNext();) { 

                } 
                 //设置Http Post数据 
                 if (params !=  null) { 
                        HttpMethodParams p =  new HttpMethodParams(); 
                         for (Map.Entry<String, String> entry : params.entrySet()) { 
                                p.setParameter(entry.getKey(), entry.getValue()); 
                        } 
                        method.setParams(p); 
                } 
                 try { 
                        client.executeMethod(method); 
                         if (method.getStatusCode() == HttpStatus.SC_OK) { 
                                response = method.getResponseBodyAsString(); 
                        } 
                }  catch (IOException e) { 
                        log.error( "执行HTTP Post请求" + url +  "时,发生异常!", e); 
                }  finally { 
                        method.releaseConnection(); 
                } 

                 return response; 
        } 

         public  static  void main(String[] args) { 
                String x = doPost( "http://lavasoft.blog.51cto.com/62575/64994", new HashMap()); 
                System.out.println(x); 
        } 
}
 
运行后打印结果如下:
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > 
< html  xmlns ="http://www.w3.org/1999/xhtml"  > 
< head > 
< meta  http-equiv ="Content-Type"   content ="text/html;  charset=gb2312" > 
< title >Java中使用正则表达式校验字符串 - 熔    岩 - 51CTO技术博客 </title> 
< meta  name ="description"  content ="Java中使用正则表达式校验字符串正则表达式是某一位伟大的数学家发明的,现在已经形成了一个ISO标准,这个标准和编程语言没有关系。至于具体谁发明的,怎么发明的,我也忘记了:)。 正则表达式简单理解就是.." > 
< meta  name ="keywords"  content ="Java中使用正则表达式校验字符串" > 
< meta  http-equiv ="Cache-Control"  content ="private" > 
< base  href ="http://lavasoft.blog.51cto.com/" > </base> 
< script  src ="/js/def.js" > </script> 
< SCRIPT language=javascript  src ="http://blog.51cto.com/js/message.js" type=text/javascript > </SCRIPT> 
< SCRIPT language=javascript  src ="http://blog.51cto.com/js/user_comment.js" type=text/javascript > </SCRIPT> 
< SCRIPT language=javascript  src ="http://blog.51cto.com/js/base2.js" type=text/javascript > </SCRIPT> 
< SCRIPT language=javascript  src ="http://blog.51cto.com/js/dialog_utf8.js" type=text/javascript > </SCRIPT> 
< link  href ="/css/skin/2.css"  rel ="stylesheet"  type ="text/css" > 
< link  href ="/css/group/group.css"  rel ="stylesheet"  type ="text/css" > 
< link  rel ="alternate"  href ="../rss.php?uid=62575"  type ="application/rss+xml"  title ="RSS 2.0" > 
< link  rel ="edituri"  type ="application/rsd+xml"  title ="rsd"  href ="xmlrpc.php?rsd=1"  /> 
< script > 
var myid = ""; 
function add_flink(){ 
  if(myid){ 
    var url='/mod/edit_flink.php?type=addflink&uid=62575&flink=http://lavasoft.blog.51cto.com'; 
    var ajax = InitAjax1(); 
    ajax.open("GET", url, true); 
    ajax.onreadystatechange = function() { 
      if (ajax.readyState == 4 && ajax.status == 200) { 
        if(ajax.responseText==""){ 
          alert("添加成功。"); 
        } 
        if(ajax.responseText=="1"){ 
        alert("链接指向自己。"); 
        } 
        if(ajax.responseText=="2"){ 
        alert("友情链接已存在。") 
        } 
      } 
    } 
    ajax.send(null); 
  }else{ 

  var refurlk = "http://lavasoft.blog.51cto.com/62575/64994";    

    commentSubmit("",refurlk); 
    return false; 
  } 
    

function sendmessage(){ 

  var refurlk = "http://lavasoft.blog.51cto.com/62575/64994";    

  if(myid){ 
    return true; 
  }else{ 
    commentSubmit("",refurlk); 
    return false; 
  } 

function copylink(ourl){ 
  if(!ourl){ 
    var clipBoardContent = "http://lavasoft.blog.51cto.com"; 
  }else{ 
    var clipBoardContent = ourl; 
  } 
  window.clipboardData.setData("Text",clipBoardContent); 
  alert("复制成功!"); 
  return false; 

function correctPNG() { 
if (document.getElementById('blog_touxian')) 

var img = document.getElementById('blog_touxian'); 
            var imgName = img.src.toUpperCase() 
            var imgID = (img.id) ? "id='" + img.id + "' " : "" 
            var imgClass = (img.className) ? "class='" + img.className + "' " : "" 
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " 
            var imgStyle = "display:inline-block;" + img.style.cssText    
            if (img.align == "left") imgStyle = "float:left;" + imgStyle 
            if (img.align == "right") imgStyle = "float:right;" + imgStyle 
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle                 
            var strNewHTML = "<span " + imgID + imgClass + imgTitle 
                 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" 
                 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" 
                 + "(src=\'" + img.src + "\', sizingMethod='scale');\"> </span>" ; 
            img.outerHTML = strNewHTML; 
}    

//window.attachEvent(" correctPNG); 
window. 
</script> 
< style  type ="text/css" > 
#layout_0{ 
  width:; 
  float:left; 

#layout_1{ 
  width:; 
  float:left; 

#layout_3{ 
  width:; 
  float:left; 

.albumalert{ 
  width:250px; 
  height:150px; 
  background:#fff; 
  border:1px solid #777; 

.alerttitle{ 
  text-align:left; 
  color:#000; 
  padding:6px; 
  background-image:url("http://img1.51cto.com/images/quickwindow.jpg"); 
  background-repeat:repeat-x; 
  font-size:14px; 
  height:22px; 

.alertcentent{ 
  line-height:30px; 

.alertcentent p{ 
color:#000; 
}
 
以上代码省略了N多行。
 
另外,我再给出一个朋友写的机器人程序,恶搞飞信诈骗网站的例子。欢迎多多运行,搞死这些骗子:
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.ProtocolException; 
import java.net.URL; 

import com.verisign.uuid.UUID; 

/** 
* 向一个飞信诈骗网站自动提交垃圾信息的程序,用空可以运行一下。 
* @author wangpeng 

*/
 
public  class AutoSubmit { 

   /** 
    * @param args 
    * @throws Exception    
    */
 
   public  static  void main(String[] args)  throws Exception { 
     for( int i=0; i < 100000; i++){ 
      post(i); 
    } 
  } 
    
   private  static  void post( int i)  throws Exception{ 
    String s = UUID.generate().toString(); 
    String s1 = s.substring(0,2); 
    s = s1+ s.substring(s.length() - 3, s.length()); 
     
    URL url =  new URL( "http://yfs88.sv10.sgedns.cn/yy/e/qq22.asp");// 提交地址 
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
    httpURLConnection.setDoOutput(true);// 打开写入属性 
    httpURLConnection.setDoInput(true);// 打开读取属性 
    httpURLConnection.setRequestMethod("POST");// 设置提交方法 
    httpURLConnection.setConnectTimeout(50000);// 连接超时时间 
    httpURLConnection.setReadTimeout(50000); 
    httpURLConnection.connect(); 
     
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "GBK")); 
    out.write("name=" + s + i +  //用户名不能重复 
        "&password=748" + 
        "&sex=日你很行" + 
        "&oicq=748748" + 
        "&icq=748748" + 
        "&msn=caonima" + 
        "&shengri=再不关门滚蛋,就把你们全关起来" + 
        "&home=已经盯上你们了");//要post的数据,多个以&符号分割 
    out.flush(); 
    out.close(); 

     

    //读取post之后的返回值 
//    BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) httpURLConnection.getInputStream())); 
//    String line = null; 
//    StringBuilder sb = new StringBuilder(); 
//    while ((line = in.readLine()) != null) { 
//      sb.append(line); 
//    } 
//    in.close(); 
//    System.out.println("client:" + sb.toString()); 
     
    httpURLConnection.disconnect();//断开连接 

    // 
    System.out.println("client post ok:" + i); 
  } 

}
 
上面程序师通过JDK的原生API实现的,很不错的一个程序。
从上面也可以看出,注册表单的验证码是多么重要了,呵呵!


本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/168276,如需转载请自行联系原作者
相关实践学习
基于Hologres轻松玩转一站式实时仓库
本场景介绍如何利用阿里云MaxCompute、实时计算Flink和交互式分析服务Hologres开发离线、实时数据融合分析的数据大屏应用。
Linux入门到精通
本套课程是从入门开始的Linux学习课程,适合初学者阅读。由浅入深案例丰富,通俗易懂。主要涉及基础的系统操作以及工作中常用的各种服务软件的应用、部署和优化。即使是零基础的学员,只要能够坚持把所有章节都学完,也一定会受益匪浅。
目录
打赏
0
0
0
0
265
分享
相关文章
了解 HTTP 的PUT 与 POST方法的综合指南
HTTP PUT 和 POST 方法是构建 Web 应用与 API 的核心工具,用于资源的创建与更新。PUT 方法通过指定 URL 更新或创建完整资源,具有幂等性;而 POST 方法更灵活,主要用于创建新资源,但不具备幂等性。本文详细对比了两者在请求体、URL 使用、资源处理等方面的区别,并提供了实际应用示例,帮助开发者根据场景选择合适的方法以优化 API 设计。
(已解决)Linux环境—bash: wget: command not found; Docker pull报错Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled
(已成功解决)Linux环境报错—bash: wget: command not found;常见Linux发行版本,Linux中yum、rpm、apt-get、wget的区别;Docker pull报错Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled
1597 68
(已解决)Linux环境—bash: wget: command not found; Docker pull报错Error response from daemon: Get https://registry-1.docker.io/v2/: net/http: request canceled
|
1月前
|
API
掌握 HTTP 请求的艺术:理解 cURL GET 语法
掌握 cURL GET 请求的语法和使用方法是 Web 开发和测试中的基本技能。通过灵活运用 cURL 提供的各种选项,可以高效地与 API 进行交互、调试网络请求,并自动化日常任务。希望本文能帮助读者更好地理解和使用 cURL,提高工作效率和代码质量。
52 7
postman发起post请求遇到报错:java.io.FileNotFoundException (文件名、目录名或卷标语法不正确。)
遇到bug报错,多猜可能的原因,控制变量反复测试,直至找到问题的关键,然后再思考如何解决或者回避。 博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
docker pull mysql:8.0.26提示Error response from daemon: Get “https://registry-1.docker.io/v2/“: EOF错误
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
148 25
java操作http请求针对不同提交方式(application/json和application/x-www-form-urlencoded)
|
4月前
|
java如何请求接口然后终止某个线程
通过本文的介绍,您应该能够理解如何在Java中请求接口并根据返回结果终止某个线程。合理使用标志位或 `interrupt`方法可以确保线程的安全终止,而处理好网络请求中的各种异常情况,可以提高程序的稳定性和可靠性。
82 6
使用OkHttp进行HTTPS请求的Kotlin实现
使用OkHttp进行HTTPS请求的Kotlin实现
http 的 get 和 post 区别 1000字
【10月更文挑战第27天】GET和POST方法各有特点,在实际应用中需要根据具体的业务需求和场景选择合适的请求方法,以确保数据的安全传输和正确处理。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等