. Net Standard HttpClient Package HTT request common operations collation

Source: Internet
Author: User

One, common HTTP operation

1.Get request, with parameters, no parameters

2.Post request, with parameters, no parameters

3. Simple File Download

    /// <summary>    ///HTTP protocol Request method Encapsulation/// </summary>     Public classNethelper {#regionGET request/// <summary>        ///GET request, no parameter/// </summary>        /// <param name= "url" ></param>        /// <returns></returns>         Public Static Asynctask<string> Getasync (stringURL) {HttpClient Client=NewHttpClient (); Httpresponsemessage resp=awaitclient.            Getasync (URL); //Get response status//respmsg.statuscode==200 Request succeeded//GET Request ContentHttpcontent respcontent =resp.            Content; return awaitRespcontent.readasstringasync (); }        /// <summary>        ///Get request, specifying parameters/// </summary>        /// <param name= "url" ></param>        /// <param name= "dic" ></param>        /// <returns></returns>         Public Static Asynctask<string> Getasync (stringURL, dictionary<string,string>dic) {//parameter HandlingStringBuilder Builder =NewStringBuilder (); Builder.            Append (URL); if(DIC. Count >0) {Builder. Append ("?"); inti =0; foreach(varIteminchdic) {if(I >0) Builder. Append ("&"); Builder. AppendFormat ("{0}={1}", item. Key, item.                    Value); I++; }            }            return awaitGetasync (builder.        ToString ()); }        /// <summary>        ///GET request-synchronous processing/// </summary>        /// <param name= "url" ></param>        /// <returns></returns>         Public Static stringGet (stringURL) {Task<string> result =getasync (URL); Result.            Wait (); returnresult.        Result; }        /// <summary>        ///GET request-synchronous processing/// </summary>        /// <param name= "url" >Request Address</param>        /// <param name= "dic" >Request Parameters</param>        /// <returns></returns>         Public Static stringGet (stringURL, dictionary<string,string>dic) {//parameter HandlingStringBuilder Builder =NewStringBuilder (); Builder.            Append (URL); if(DIC. Count >0) {Builder. Append ("?"); inti =0; foreach(varIteminchdic) {if(I >0) Builder. Append ("&"); Builder. AppendFormat ("{0}={1}", item. Key, item.                    Value); I++; }            }            returnGet (builder.        ToString ()); }        #endregion        #regionPost Request Processing/// <summary>        ///Post request, no reference/// </summary>        /// <param name= "url" ></param>        /// <returns></returns>         Public Static Asynctask<string> Postasync (stringUrlstringContent ="") {HttpClient client=NewHttpClient (); using(MemoryStream ms =NewMemoryStream ()) {                byte[] bytes =Encoding.Unicode.GetBytes (content); Ms. Write (Bytes,0, Bytes.                Length); Httpcontent HC=Newstreamcontent (MS); Httpresponsemessage resp=awaitClient. Postasync (URL,NULL); return awaitresp.            Content.readasstringasync (); }        }        /// <summary>        ///Post request, processing parameters/// </summary>        /// <param name= "url" ></param>        /// <param name= "dic" ></param>        /// <returns></returns>         Public Static Asynctask<string> Postasync (stringURL, dictionary<string,string>dic) {HttpClient client=NewHttpClient (); Formurlencodedcontent Data=Newformurlencodedcontent (DIC); varR =awaitclient.            Postasync (URL, data); return awaitR.content.readasstringasync (); //client.            DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("text/html")); //client.            DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/xhtml+xml")); //client.            DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/xml", 0.9)); //client.            DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("IMAGE/WEBP")); //client.            DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("*/*", 0.8)); //HC. Headers.add ("useragent", "mozilla/5.0" (Windows NT 6.1;            WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/31.0.1650.57 safari/537.36 "); //HC.            Headers.add ("Timeout", timeout.tostring ()); //HC. Headers.add ("KeepAlive", "true");        }        /// <summary>        ///POST request, synchronous, no parameter/// </summary>        /// <param name= "url" ></param>        /// <param name= "content" ></param>        /// <returns></returns>         Public Static stringPost (stringUrlstringContent ="") {Task<string> str =postasync (URL, content); Str.            Wait (); returnStr.        Result; }        /// <summary>        ///Post request, synchronization, parameter handling/// </summary>        /// <param name= "url" ></param>        /// <param name= "dic" ></param>        /// <returns></returns>         Public Static stringPost (stringURL, dictionary<string,string>dic) {Task<string> str =postasync (URL, dic); Str.            Wait (); returnStr.        Result; }        #endregion        #regionDownload file processing/// <summary>        ///Download File/// </summary>        /// <param name= "url" >Link Address</param>        /// <param name= "target" >Storage Address</param>        /// <returns></returns>         Public Static BOOLDownLoad (stringUrlstringtarget) {            Try{HttpClient Client=NewHttpClient (); vart =client.                Getbytearrayasync (URL);                T.wait (); varbytes =T.result; using(FileStream fs =NewFileStream (target, FileMode.Create)) {fs. Write (Bytes,0, Bytes.                    Length); Fs.                Close (); }                return true; }            Catch(Exception ex) {Throw NewException ("failed to download the file,", ex); }        }        #endregion    }

More:

Creation and use of the. Net Standard Class Library

. Net Standard HTTP Request instance

Introduction to. Net Standard

. Net Standard HttpClient Package HTT request common operations collation

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.