有人能指出我使用 Windows Phone 8 <如何 POST JSON到RESTful API(例如Web API)的工作示例/ EM> ?我有一个GET的工作示例,但似乎找不到任何有关POST的工作示例。我发现的所有针对C#的POST示例都不适用于Windows Phone 8(由于剥离的.NET框架)。
答案 0 :(得分:3)
好的,我终于能够提出一个有效的解决方案,所以我想将其发布回来以保证完整性。但是,如果有人知道在Windows Phone 8中更好的方法,我很乐意看到它!
public void SendPost(Uri uri, string json)
{
var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.UploadStringCompleted += this.sendPostCompleted;
webClient.UploadStringAsync(uri, "POST", json);
}
private void sendPostCompleted(object sender, UploadStringCompletedEventArgs e)
{
// Handle result
Console.WriteLine("HTTP POST Result: {0}", e.Result);
}
答案 1 :(得分:0)
最好的方法是使用Restsharp:
Dim client As New RestSharp.RestClient("https://stuff.com/api/") Dim req As New RestSharp.RestRequest("dothings", Method.POST) req.RequestFormat = DataFormat.Json req.AddBody(New reqAuth With {.param1 = "stuff1", .param2= "stuff2"}) client.ExecuteAsync(req, Sub(res) Console.WriteLine(res.Content) End Sub)
答案 2 :(得分:0)
string email = txtEmailAddress.Text;
string password = txtPassword.Text;
string confirmPassword = txtConfirmPassword.Text;
string dd = txtDD.Text;
string mm = txtMM.Text;
string yyyy = txtYYYY.Text;
UserDetails ud = new UserDetails
{
DateofBirth = DateTime.Now.ToString(),
EmailAddress=email,
Password=password,
ProfileImage="",
UserID="0"
};
WebClient wc = new WebClient();
wc.Headers["Content-Type"] = "application/json";
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer serializertoUpload = new DataContractJsonSerializer(typeof(UserDetails));
serializertoUpload.WriteObject(ms, ud);
string data = Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
wc.UploadStringAsync(new Uri("<wcfserviceurl>"), "POST", data);
以下是UserDetails类的定义
public class UserDetails
{
public string UserID { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
public string DateofBirth { get; set; }
public string ProfileImage { get; set; }
}
答案 3 :(得分:-1)
public async void makeRequest(String resourceUri)
{
HttpClient httpClient = new HttpClient();
try
{
HttpResponseMessage response = await httpClient.GetAsync(resourceUri);
}
catch (HttpRequestException hre)
{
Console.Write(hre.Message);
}
catch (TaskCanceledException)
{
}
}
记得添加Nuget包:httpclient