About .NET HttpClient way to get small micro-channel program code (two-dimensional code)

With the application of micro fiery letter applet, applet development related to the market demand is also more up. Recent analysis of a small micro-channel generation generate program code related needs - requires scan code to jump to a specific page small program (with parameters); applet official documents, as well as online examples looked at how much valuable not see examples of the use of C # to call a small applet program interface to generate code, so the code picked up years ago, slightly analysis attempts to share in this people in need, and thus start a discussion.

HttpClient way of example text, of course, also be employed HttpWebRequest old, will not be analyzed here.
Applet code generating micro-channel (two-dimensional code) There are three interfaces:

In this respect only createwxaqrcode (two-dimensional code), and get (small procedure code / sunflower yards) explain, getUnlimited same principle;

Address of the interface between the two are as follows:

https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN

https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN

Since the request small program interface that returns a binary image stream using sure processed for binary data HttpClient embodiment; much to say, directly on the key code, the following example briefly:

 

public class HttpClientHelper
    {
public static bool DownloadBufferImage(string requestUri, /*HttpContent httpContent,*/string filePath, string jsonString, string webapiBaseUrl = "")
        {
            try
            {
                HttpContent httpContent = new StringContent(jsonString);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
               
                using (HttpClient httpClient = new HttpClient())
                {                   
                    if (!string.IsNullOrWhiteSpace(webapiBaseUrl))
                    {
                        httpClient.BaseAddress = new Uri(webapiBaseUrl);
                    }
                    bool result = false;
                    httpClient.PostAsync(requestUri, httpContent).ContinueWith(
                       (requestTask) =>
                       {
                           HttpResponseMessage response = requestTask.Result;

                           response.EnsureSuccessStatusCode();

                           var data = response.Content.ReadAsByteArrayAsync().Result;
                        
                           using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                           {
                               fs.Write(data, 0, data.Length);
                               fs.Flush();
                               fs.Close();
                           }

                           result = true;

                       }).Wait(30000);
                 
                    return result;
                }
            }
            catch
            {
                return false;
            }
        }
}

  

A total of four parameters:

  1. Interface URL requestUri request;
  2. Absolute path filePath applet code (two-dimensional code) stored;
  3. json jsonString submitted data object;
  4. webapiBaseUrl root Interface (negligible)

 

Since Tencent interface requirements, must submit data json objects, httpContent.Headers.ContentType = new MediaTypeHeaderValue ( "application / json"), here especially important, as not submit form in the form dictionary as submitted manner; secondly, binary data stream take the form of processing and storing the image; not repeated here.

var data = response.Content.ReadAsByteArrayAsync().Result;
                        
                           using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                           {
                               fs.Write(data, 0, data.Length);
                               fs.Flush();
                               fs.Close();
                           }

  

Brief package and call the following example:

public bool GetQrCode(string filePath, string path = "pages/default/default", int width = 430)
         {
             string postUrl = string.Format("https://api.weixin.qq.com/wxa/getwxacode?access_token={0}", AccessToken);         

             var data = new
            {
                path = path,
                width = width
            };
             var result = HttpClientHelper.DownloadBufferImage(postUrl, filePath, Newtonsoft.Json.JsonConvert.SerializeObject(data));

             return result;
         } 

  

new NameSpace.GetQrCode(@"D:\QrCode.jpg", path: "pages/index/index");

 

filePath for the preservation of the applet code (two-dimensional code) picture of absolute path, such as Server.MapPath (savePath); path (applet page address) and width (width of the two-dimensional code, default 430) are optional parameters, see the specific interface documentation; the AccessToken interface calls for the voucher;

Note: Due to restrictions Tencent, if the interface call is successful, it will return to direct the picture binary content, if the request fails, it returns data in JSON format; method where only return a binary stream for processing, according to the needs of other self-improvement.

 

Guess you like

Origin www.cnblogs.com/ang/p/11620940.html