Asp.net WebRequest Post and Get data instances

Source: Internet
Author: User

WebRequest Post and Get data are some problems that may occur during. net development. Let's take a look at some of the following examples. Sqlserver/42852.htm target = _ blank>

The Code is as follows: Copy code

 

Public class WebRequestHelper
{
/// <Summary>
/// Request data in the form of POST
/// </Summary>
/// <Param name = "RequestPara"> </param>
/// <Param name = "Url"> </param>
/// <Returns> </returns>
Public static string PostData (string RequestPara, string Url)
{
WebRequest hr = HttpWebRequest. Create (Url );
 
Byte [] buf = System. Text. Encoding. GetEncoding ("UTF-8"). GetBytes (RequestPara );
Hr. ContentType = "application/x-www-form-urlencoded ";
Hr. ContentLength = buf. Length;
Hr. Method = "POST ";
 
System. IO. Stream RequestStream = hr. GetRequestStream ();
RequestStream. Write (buf, 0, buf. Length );
RequestStream. Close ();
 
System. Net. WebResponse response = hr. GetResponse ();
StreamReader reader = new StreamReader (response. GetResponseStream (), Encoding. GetEncoding ("UTF-8 "));
String ReturnVal = reader. ReadToEnd ();
Reader. Close ();
Response. Close ();
 
Return ReturnVal;
}
 
/// <Summary>
/// GET data in the form of GET
/// </Summary>
/// <Param name = "RequestPara"> </param>
/// <Param name = "Url"> </param>
/// <Returns> </returns>
 
Public static string GetData (string RequestPara, string Url)
{
RequestPara = RequestPara. IndexOf ('? ')>-1? (RequestPara ):("? "+ RequestPara );
 
WebRequest hr = HttpWebRequest. Create (Url + RequestPara );
 
Byte [] buf = System. Text. Encoding. GetEncoding ("UTF-8"). GetBytes (RequestPara );
Hr. Method = "GET ";
 
System. Net. WebResponse response = hr. GetResponse ();
StreamReader reader = new StreamReader (response. GetResponseStream (), Encoding. GetEncoding ("UTF-8 "));
String ReturnVal = reader. ReadToEnd ();
Reader. Close ();
Response. Close ();
 
Return ReturnVal;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.