首页 > 编程 > .NET > 正文

在.NET 中模拟提交Post数据

2024-07-10 12:59:17
字体:
来源:转载
供稿:网友
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();
}
}
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表