The encoding problem generated by the POST request from the service side

Source: Internet
Author: User

Recently in doing a function, presumably the function is this, the supplier provides HTTP interface to us, then we crawl the supplier's data to save to the database, the problem is that their encoding format is gb2312, and we are utf-8.

You may have a misunderstanding that the POST request is not encoded, but in fact, as long as in the HTTP request header "Content-type" as "application/x-www-form-urlencoded, The current encoding format will be used before the UrlEncode interface. So if the front-end post data to the backend, the front end is gb2312 encoded format, the back end is Utf-8, just set in Content-type, Application/x-www-form-urlencoded;charset=utf-8.

And we're the service-side direct interface, and I'm using Restsharp.

var request = new Restrequest (method.post); request. Requestformat = Dataformat.json;request. Addbody (model), var client = new Restclient ("Http://localhost:2290/Interface/Index"), var response = client. Execute (request); return response. Content;

Flipping through documents, this period will automatically urlencode ...

Later try to set the Web. config, set the default encoding format, encoding problem still can't solve, there is a impulse want to see Restsharp source, but time is too late ah .... (Be sure to check it sometime)

<globalization requestencoding= "gb2312" responseencoding= "gb2312"/>

The

Finally found a solution, using. NET source to httprequest 

        <summary>///HTTP request to create POST method///</summary>//<param name= "url" &G T; the requested url</param>//<param name= "Parameters" > a dictionary of parameter names and parameter values accompanying the request post </param>//<para          M name= "Timeout" > timeout for request </param>//<param name= "useragent" > requested client browser information, can be null </param> <param name= "requestencoding" > Encoding used to send HTTP requests </param>//<param name= "cookies" > with HTTP Requests  Send cookie information If authentication is not required can be empty </param>///<returns></returns> public static HttpWebResponse Createposthttpresponse (string URL, idictionary<string, string> parameters, int? Timeout, string useragent, Encoding requestencoding, cookiecollection cookies) {if (string.            IsNullOrEmpty (URL)) {throw new ArgumentNullException ("url"); } if (requestencoding = = null) {throw new ArgumentnullexCeption ("requestencoding");            } HttpWebRequest request = null; If the HTTPS request is sent if (URL. StartsWith ("https", StringComparison.OrdinalIgnoreCase)) {Servicepointmanager.servercertificate                ValidationCallback = new Remotecertificatevalidationcallback (CheckValidationResult);                Request = WebRequest.Create (URL) as HttpWebRequest; Request.            ProtocolVersion = Httpversion.version10;            } else {request = WebRequest.Create (URL) as HttpWebRequest; } request.            Method = "POST"; Request.            ContentType = "application/x-www-form-urlencoded"; if (!string. IsNullOrEmpty (useragent)) {request.            useragent = useragent; } else {request.            useragent = defaultuseragent; } if (timeout. HasValue) {request. Timeout = timeout. VAlue; } if (cookie = null) {request.                Cookiecontainer = new Cookiecontainer (); Request.            Cookiecontainer.add (cookies); }//If you need post data if (!) ( Parameters = = NULL | | Parameters.                Count = = 0) {StringBuilder buffer = new StringBuilder ();                int i = 0; foreach (string key in Parameters. Keys) {if (i > 0) {buffer.                    AppendFormat ("&{0}={1}", Key, Parameters[key]); } else {buffer.                    AppendFormat ("{0}={1}", Key, Parameters[key]);                } i++; } byte[] data = requestencoding.getbytes (buffer.                ToString ()); using (Stream stream = Request. GetRequestStream ()) {stream. Write (data, 0, data. LenGTH); }} return request.        GetResponse () as HttpWebResponse; }

The call is as follows:

            idictionary<string, string> parameters = new dictionary<string, string> ();            Parameters. ADD ("Requestjson", jsonstr);            HttpWebResponse response = httpwebresponseutility.createposthttpresponse (URL, parameters, NULL, NULL, Encoding.GetEncoding ("GB2312"), null);            using (StreamReader reader = new StreamReader (response. GetResponseStream (), System.Text.Encoding.UTF8))            {                strres = reader. ReadToEnd ();            }

  

The encoding problem generated by the POST request from the service side

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.