在.NET 中類比提交Post資料

來源:互聯網
上載者:User
資料 using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web;

class ClientPOST {
public static void Main(string[] args) {

if (args.Length < 1) {
showusage();
} else {
if (args.Length < 2 ) {
getPage(args[0], "s1=foods2=bart(&S)");
} else {
getPage(args[0], args[1]);
}
}

Console.WriteLine();
Console.WriteLine("按任意鍵繼續...");
Console.ReadLine();

return;
}

public static void showusage() {
Console.WriteLine("嘗試發送 (POST) 到 URL 中");
Console.WriteLine();
Console.WriteLine("用法::");
Console.WriteLine("ClientPOST URL [postdata]");
Console.WriteLine();
Console.WriteLine("樣本::");
Console.WriteLine("ClientPOST http://www.microsoft.com s1=food&s2=bart");
}

public static void getPage(String url, String payload) {
WebResponse result = null;

try {

WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
StringBuilder UrlEncoded = new StringBuilder();
Char[] reserved = {'?', '=', '&'};
byte[] SomeBytes = null;

if (payload != null) {
int i=0, j;
while(i<payload.Length){
j=payload.IndexOfAny(reserved, i);
if (j==-1){
UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, payload.Length-i)));
break;
}
UrlEncoded.Append(HttpUtility.UrlEncode(payload.Substring(i, j-i)));
UrlEncoded.Append(payload.Substring(j,1));
i = j+1;
}
SomeBytes = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
req.ContentLength = SomeBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
} else {
req.ContentLength = 0;
}


result = req.GetResponse();
Stream ReceiveStream = result.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader sr = new StreamReader( ReceiveStream, encode );
Console.WriteLine("\r\n已接收到響應流");
Char[] read = new Char[256];
int count = sr.Read( read, 0, 256 );
Console.WriteLine("HTML...\r\n");
while (count > 0) {
String str = new String(read, 0, count);
Console.Write(str);
count = sr.Read(read, 0, 256);
}
Console.WriteLine("");
} catch(Exception e) {
Console.WriteLine( e.ToString());
Console.WriteLine("\r\n找不到請求 URI,或者它的格式不正確");
} finally {
if ( result != null ) {
result.Close();
}
}
}
}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.