通过SendRequestAsync在正文中发送字符串

问题描述

我需要通过SendRequestAsync函数将补丁请求发送到后端API。这与UWP C#应用有关。

后端希望像这样:

enter image description here

在应用程序上,这是我编写的代码。但不起作用

if (requestMehtod == ApplicationConstants.RequestType.PATCH)
            {
                Uri uri = new Uri(requestUrl);
                HttpRequestMessage requestMessage = null;
                if (postData != null)
                {
                    var itemAsJson = JsonConvert.SerializeObject(postData);

                    requestMessage = new HttpRequestMessage(HttpMethod.Patch,uri)
                    {
                        Content = new HttpStringContent(itemAsJson,Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/json-patch+json")
                    };
                }
                else
                {
                    requestMessage = new HttpRequestMessage(HttpMethod.Patch,uri);
                }

                response = await httpClient.SendRequestAsync(requestMessage).AsTask(cancellationTokenSource.Token);
                var rdModel = ProcessResponseData(response);
                return await Handle401Error(rdModel,response,postData,url,requestMehtod,isDownloadSite,OnSendRequestProgress,requestData);
            }

上面的代码可以将JSON数据发送到相同的API,并且可以正常工作。但是我需要知道如何仅在体内发送一个琴弦。感谢您的考虑

注意:应用程序使用Windows.Web.Http中的HttpClient,将无法使用System.Net.Http命名空间中的任何内容

解决方法

答案由@gusman和@Simon Wilson提供。为了修正他们的答案,为了能够在请求正文中发送字符串,该字符串必须在双引号内。

var requestData = "\"hello world\"";
var request = new HttpRequestMessage(HttpMethod.Post,uri)
                    {
                        Content = new HttpStringContent(requestData,Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/json")
                    };
                    response = await httpClient.SendRequestAsync(request);

这在我的情况下有效。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...