Several ways to implement the post and get of HTTP

Source: Internet
Author: User

</pre></p><p></p><pre class= "CSharp" name= "code" ><strong><span style= " Color: #ff0000; " >1.post method (HttpWebRequest) </span></strong>

#region Post Method (HttpWebRequest)//body is the parameter to be passed, the format "roleid=1&uid=2"//post cotenttype Fill in://"application/ x-www-form-urlencoded "//soap fill in:" Text/xml; Charset=utf-8 "public static string posthttp (string URL, string body, string contentType) {HttpWebRequest HT        Tpwebrequest = (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; } #endregion
</pre></p><p></p><pre class= "CSharp" name= "code" ><strong><span style= " Color: #ff0000; " >2.post method (WebClient) </span></strong>

<summary>       ////via WebClient class post data to remote address, Basic authentication is required;        ///The caller handles exceptions themselves        //</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)         {&NBSP;&NBSP;&NBSP;&Nbsp;        if (encoding = = NULL)                  encoding = Encoding.UTF8;
string result = String. Empty;
WebClient WC = new WebClient ();
The header WC must be added to the post method. 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); Gets the return character stream return encoding. GetString (responsedata);//decoding}
</pre></p><p></p><pre class= "CSharp" name= "code" ><strong><span style= " Color: #ff0000; " >3.get method (HttpWebRequest) </span></strong>

         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; }
</pre></p><p></p><pre class= "CSharp" name= "code" ><strong><span style= " Color: #ff0000; " >4.basic verified Webrequest/webresponse</span></strong>

        <summary>       ////Access remote address via Webrequest/webresponse class and return results, Basic authentication required ;       ///caller handle exception        ///</ summary>       //<param name= "uri" ></param>        //<param name= "Timeout" > Access time-out, unit milliseconds, if no timeout is set, incoming 0</param>        //<param name= "encoding" > If you do not know the specific encoding, 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


Several ways to implement the post and get of HTTP

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.