HttpRequest Get和Post调用其他页面的方法
//get请求方式
private string requestget(string url)
{
string pagestr = string.empty;//用于存放还回的html
uri url = new uri(url);//uri类 提供统一资源标识符 (uri) 的对象表示形式和对 uri 各部分的轻松访问。就是处理url地址
try
{
httpwebrequest httprequest = (httpwebrequest)webrequest.create(url);//根据url地址创建httpwebrequest对象
#region 参数设置
httprequest.method = "get";
//---------------------------------------------设定一些参数(不必要可以)
//httprequest.keepalive = false;//持久连接设置为false
//httprequest.protocolversion = httpversion.version11;// 网络协议的版本
//httprequest.proxy = webproxy.getdefaultproxy();//服务器代理
//httprequest.contenttype = "application/x-www-form-urlencoded";//http 头
//httprequest.allowautoredirect = true;
//httprequest.maximumautomaticredirections = 10;
//httprequest.timeout = 30000;//设定超时十秒(毫秒)
//httprequest.useragent = "mozilla/4.0 (compatible; msie 6.0; windows nt 5.1)"; //浏览器
//=================================================
#endregion
httpwebresponse response = (httpwebresponse)httprequest.getresponse();//使用httpwebresponse获取请求的还回值
stream steam = response.getresponsestream();//从还回对象中获取数据流
streamreader reader = new streamreader(steam, encoding.getencoding("gb2312"));//读取数据encoding.getencoding("gb2312")指编码是gb2312,不让中文会乱码的
pagestr = reader.readtoend();
reader.close();
}
catch (exception e)
{
pagestr += e.message;
}
return pagestr;
}
//post请求方式,于get的方式写法相似,所以解释就些少一点了
private string requestpost(string url,string context)//两个参数分别是url地址和post过去的数据
{
string pagestr=string.empty;
uri url = new uri(url);
byte[] reqbytes=encoding.ascii.getbytes(context);
try
{
httpwebrequest req = (httpwebrequest)webrequest.create(url);
req.method = "post";
req.contenttype = "application/x-www-form-urlencoded";
req.contentlength = reqbytes.length;
stream stm = req.getrequeststream();
stm.write(reqbytes, 0, reqbytes.length);
stm.close();
httpwebresponse wr = (httpwebresponse)req.getresponse();
stream stream = wr.getresponsestream();
streamreader srd= new streamreader(stream,encoding.getencoding("gb2312"));
pagestr += srd.readtoend();
stream.close();
srd.close();
}
catch (exception e)
{
pagestr += e.message;
}
return pagestr;
}
public string webclientget(string url)
{
var client = new webclient();
client.headers.add("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.2; .net clr 1.0.3705;)");
var stream = client.openread(url);
if (stream == null) return "";
var reader = new streamreader(stream, encoding.default);
var result = reader.readtoend();
stream.close();
reader.close();
return result;
}
上一篇: python连接数据库的方法
下一篇: Java中的静态绑定和动态绑定详细介绍
推荐阅读
-
HttpRequest Get和Post调用其他页面的方法
-
php中运用http调用的GET和POST方法示例,getpost
-
php中运用http调用的GET和POST方法示例_PHP
-
jQuery调用AJAX时Get和post公用的乱码解决方法实例说明
-
php中运用http调用的GET和POST方法示例
-
jQuery调用AJAX时Get和post公用的乱码解决方法实例说明
-
php中运用http调用的GET和POST方法示例,getpost
-
php中运用http调用的GET和POST方法示例,getpost_PHP教程
-
php中运用http调用的GET和POST方法示例_PHP
-
js调用AJAX时Get和post的乱码解决方法_javascript技巧