On.NET HttpClient way to get small code (Er Weima)

Keywords: ASP.NET JSON QRCode

With the hot application of small programs, there are many demands for small program development on the market. Recently, we analyzed the requirement of generating a small program code, which required that scan code jump to the specified page of the small program (with parameters). After looking at the official document of the small program and the example on the Internet, we didn't see many valuable examples of using C# to call the small program interface to generate small program code. Those who need it, and use it to attract others.

This article takes the HttpClient mode as an example, of course, the old HttpWebRequest can also be used, and will not be analyzed here.
There are mainly three interfaces to generate small code (two-dimensional code):

This is only for createwxaqrcode (Er Weima) and get (small program code / sunflower code) to explain, getUnlimited principle is the same.

The interface addresses of 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

Due to the request of the small program interface, it returns the image binary stream. When using HttpClient mode, it is necessary to process the binary data. Needless to say, directly to the key code, a brief example is as follows:

 

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;
            }
        }
}

  

There are four parameters in total:

  1. The interface URL requested by requestUri;
  2. The absolute path stored by filePath widget code (two-dimensional code);
  3. json data object submitted by jsonString;
  4. Web apiBaseUrl interface root path (negligible)

 

Because of the request of the interface, data must be submitted to JSON object, so httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"), which is particularly important here, can not be submitted in a dictionary way as submitted to form form; secondly, processing binary data stream in the following way to process and save pictures; do not repeat 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();
                           }

  

A brief example of encapsulation and invocation is as follows:

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 is the absolute path to save pictures of small program codes, such as Server.MapPath(savePath); path (page address of small program) and width (two-dimensional code width, default 430) are optional parameters, see the interface document specifically; AccessToken is the interface invocation credentials;

Note: because of the restriction, if the interface invocation is successful, the binary content of the picture will be returned directly. If the request fails, it will return the data in JSON format. The method only deals with the return binary stream, and the other can be perfected according to the requirement.

Posted by Edgewalker81 on Sat, 05 Oct 2019 16:31:18 -0700