public static async Task<string> GetData(string url, string data)
{
UriBuilder fullUri = new UriBuilder(url);
if (!string.IsNullOrEmpty(data))
fullUri.Query = data;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(new Uri(url), /*expects HttpContent*/);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
Run Code Online (Sandbox Code Playgroud)
将PostAsync采取一个需要另一个参数HttpContent.
我该如何设置HttpContent?任何适用于Windows Phone 8的文档都没有.
如果我这样做GetAsync,那就太棒了!但它需要POST的内容为key ="bla",某事="yay"
//编辑
非常感谢答案......这很有效,但这里还有一些不确定的地方:
public static async Task<string> GetData(string url, string data)
{
data = "test=something";
HttpClient client = new HttpClient();
StringContent queryString …Run Code Online (Sandbox Code Playgroud) 我正在开发一个wp8.1应用程序C#,我已经设法通过从textbox.texts创建一个json对象(bm)来在json中执行一个POST方法到我的api.这是我的代码如下.我如何使用相同的textbox.text并将它们作为内容类型= application/x-www-form-urlencoded进行POST.那是什么代码?
Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;
string json = JsonConvert.SerializeObject(bm);
MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
Run Code Online (Sandbox Code Playgroud)