一个WebApi请求示例

各种参数都没问题,但是WebApi请求却有问题,排查了很久,终于解决了。
原来是Http请求头中一个参数“Content-Type”需要如此设置.

private static HttpClient httpClient = new HttpClient();
public string GetHttpByte(string method, object obj)
        {
            GetToken();
            var plainText = JsonSerializer.Serialize(obj);
            var sm4String = SM4.Encrypt(plainText, SM4Key);
            var sm3String = SM3.Hash(sm4String).ToLower();

            var url = $"http://{ServerIP}:{ServerPort}/openplartform/business/{method}";
            var request = new HttpRequestMessage();
            request.RequestUri = new Uri(url);
            request.Method = HttpMethod.Post;
            request.Headers.Add("ContentType", "application/json; charset=UTF-8");
            request.Headers.Add("Token", token?.resultData?.token);
            request.Headers.Add("sign", sm3String);

            var stringContent = new StringContent(sm4String);
            stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content = stringContent;

            var response = httpClient.SendAsync(request);
            var result = response.Result.Content.ReadAsByteArrayAsync();
            var data = result.Result;
            var err = Encoding.UTF8.GetString(data);
            var queryBasicInfo = JsonSerializer.Deserialize<QueryBasicInfo>(data);

            var resultData = SM4.Decrypt(queryBasicInfo.resultData, SM4Key);
#if DEBUG
            Console.WriteLine("method name:\t" + method);
            Console.WriteLine("post message:\t" + plainText);
            Console.WriteLine("sm4String:\t" + sm4String);
            Console.WriteLine("sm3String:\t" + sm3String);
            Console.WriteLine("resultData:\t" + resultData);
            Console.WriteLine("message:\t" + queryBasicInfo.message);
            Console.WriteLine("success:\t" + queryBasicInfo.success);
            Console.WriteLine("client time:\t" + DateTime.Now);
            Console.WriteLine("server time:\t" + response.Result.Headers.Date.Value.AddHours(8));
            Console.WriteLine();
#endif
            return resultData;
        }

一件事情终于完成了。

你可能感兴趣的:(C#技术,javascript,开发语言,ecmascript)