Java類比HTTP的Get和Post請求

來源:互聯網
上載者:User

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;

 

 


public final class HttpTookit {
        private static Log log = LogFactory.getLog(HttpTookit.class);

 

 

       
        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;
        }

 

 

       
        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中使用Regex校正字串 - 熔    岩 - 51CTO技術部落格</title>
<meta name="description" content="Java中使用Regex校正字串Regex是某一位偉大的數學家發明的,現在已經形成了一個ISO標準,這個標準和程式設計語言沒有關係。至於具體誰發明的,怎麼發明的,我也忘記了:)。Regex簡單理解就是..">
<meta name="keywords" content="Java中使用Regex校正字串">
<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;

 

 


public class AutoSubmit {

 

 

 
  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);
  }

 

 

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.