C # Post/get method for implementing HTTP through Webclient/httpwebrequest

Source: Internet
Author: User

Body is the parameter to be passed, the format "roleid=1&uid=2"
Post Cotenttype fill in:
"Application/x-www-form-urlencoded"
Soap fills in: "Text/xml; Charset=utf-8 "
public static string posthttp (string URL, string body, string contentType)
{
HttpWebRequest HttpWebRequest = (HttpWebRequest) webrequest.create (URL);

Httpwebrequest.contenttype = ContentType;
Httpwebrequest.method = "POST";
Httpwebrequest.timeout = 20000;

byte[] Btbodys = Encoding.UTF8.GetBytes (body);
Httpwebrequest.contentlength = Btbodys.length;
Httpwebrequest.getrequeststream (). Write (Btbodys, 0, btbodys.length);

HttpWebResponse HttpWebResponse = (HttpWebResponse) httpwebrequest.getresponse ();
StreamReader StreamReader = new StreamReader (Httpwebresponse.getresponsestream ());
String responsecontent = Streamreader.readtoend ();

Httpwebresponse.close ();
Streamreader.close ();
Httpwebrequest.abort ();
Httpwebresponse.close ();

return responsecontent;
}

Post Method (HttpWebRequest)

<summary>
Basic authentication is required by WebClient post data to remote address;
The caller handles the exception itself
</summary>
<param name= "uri" ></param>
<param name= "Paramstr" >name= Zhang San &age=20</param>
<param name= "Encoding" > Please first confirm the encoding of the target page </param>
<param name= "username" ></param>
<param name= "Password" ></param>
<returns></returns>
public static string Request_webclient (String uri, String paramstr, Encoding Encoding, string Username, string password)
{
if (encoding = = NULL)
encoding = Encoding.UTF8;

string result = String. Empty;

WebClient WC = new WebClient ();

The header that must be added in the post mode
Wc. Headers.add ("Content-type", "application/x-www-form-urlencoded");

byte[] PostData = encoding. GetBytes (PARAMSTR);

if (!string. IsNullOrEmpty (username) &&!string. IsNullOrEmpty (password))
{
Wc. Credentials = Getcredentialcache (URI, username, password);
Wc. Headers.add ("Authorization", getauthorization (username, password));
}

byte[] ResponseData = WC. Uploaddata (URI, "POST", postdata); Get a stream of returned characters
return encoding. GetString (responsedata);//decoding
}

Post Method (WebClient)

public static string gethttp (string URL, HttpContext HttpContext)
{
String queryString = "?";

foreach (string key in HttpContext.Request.QueryString.AllKeys)
{
QueryString + = key + "=" + Httpcontext.request.querystring[key] + "&";
}

queryString = querystring.substring (0, querystring.length-1);

HttpWebRequest HttpWebRequest = (HttpWebRequest) webrequest.create (url + queryString);

Httpwebrequest.contenttype = "Application/json";
Httpwebrequest.method = "GET";
Httpwebrequest.timeout = 20000;

byte[] Btbodys = Encoding.UTF8.GetBytes (body);
Httpwebrequest.contentlength = Btbodys.length;
Httpwebrequest.getrequeststream (). Write (Btbodys, 0, btbodys.length);

HttpWebResponse HttpWebResponse = (HttpWebResponse) httpwebrequest.getresponse ();
StreamReader StreamReader = new StreamReader (Httpwebresponse.getresponsestream ());
String responsecontent = Streamreader.readtoend ();

Httpwebresponse.close ();
Streamreader.close ();

return responsecontent;
}

Get Method (HttpWebRequest)

<summary>
The Webrequest/webresponse class accesses the remote address and returns the result, requiring basic authentication;
The caller handles the exception itself
</summary>
<param name= "uri" ></param>
<param name= "Timeout" > Access timeout, unit milliseconds, if no time-out is set, incoming 0</param>
<param name= "Encoding" > if the specific encoding is not known, the incoming null</param>
<param name= "username" ></param>
<param name= "Password" ></param>
<returns></returns>
public static string Request_webrequest (string uri, int timeout, Encoding Encoding, string Username, string password)
{
string result = String. Empty;

WebRequest request = WebRequest.Create (new Uri (URI));

if (!string. IsNullOrEmpty (username) &&!string. IsNullOrEmpty (password))
{
Request. Credentials = Getcredentialcache (URI, username, password);
Request. Headers.add ("Authorization", getauthorization (username, password));
}

if (Timeout > 0)
Request. Timeout = timeout;

WebResponse response = Request. GetResponse ();
Stream stream = Response. GetResponseStream ();
StreamReader sr = encoding = = NULL? New StreamReader (Stream): New StreamReader (stream, encoding);

result = Sr. ReadToEnd ();

Sr. Close ();
Stream. Close ();

return result;
}

#region # Generate Http Basic Access Credentials #

private static CredentialCache Getcredentialcache (string uri, string Username, string password)
{
string authorization = string. Format ("{0}:{1}", username, password);

CredentialCache Credcache = new CredentialCache ();
Credcache.add (new Uri (URI), "Basic", new NetworkCredential (username, password));

return credcache;
}

private static string Getauthorization (string username, string password)
{
string authorization = string. Format ("{0}:{1}", username, password);

Return "Basic" + convert.tobase64string (new ASCIIEncoding (). GetBytes (authorization));
}

#endregion

Webrequest/webresponse of basic validation

C # Post/get method for implementing HTTP through Webclient/httpwebrequest

Related Article

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.