我想通过 HTTPS POST 将 JSON 多部分数据发送到
C#
中的 webservice-url。
JSON:
info = {
fullname:"Name sername",
code:"123465",
code2:"12346",
code3:"1234567"
}
如何发送到
C#
中的url?
这是一个示例。
public async Task<String> GetData()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Statics.Baseurl);
//The base Url is the Http Post request url (base) eg: http://www.example.com/
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Info info = new Info();
info.fullname = "Name surname";
info.code = "123465";
info.code2 = "123465";
info.code3 = "123465";
//JsonCOnvert.SerilizeObject() will convert your custom class to JSON
StringContent content = new StringContent(JsonConvert.SerializeObject(info), Encoding.UTF8, "application/json");
//the base address already defined in the client
//This is the remaining part of the address.
//We are passing the JSON value to the HTTP POST here.
HttpResponseMessage Res = await client.PostAsync("api/Worker/GetDetails", content);
if (Res.IsSuccessStatusCode)
{
var response = Res.Content.ReadAsStringAsync().Result;
return response;
}
else
{
return "No_Data";
}
}
}
在上面的例子中,有一个类
Info
,可以如下定义。
public class Info
{
public String fullname { get; set; }
public String code { get; set; }
public String code2 { get; set; }
public String code3 { get; set; }
}
注:
HttpClient
类可以在System.Net.Http
命名空间下找到asp.net Web 表单中使用
RegisterAsyncTask
来触发 async
方法。请参阅此处了解更多详情。试试这个,它有效。
var client = new RestClient("http://www.google.com");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "7ef33df4-9c36-4e92-9390-8fd17274d32d");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("content-type", "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW");
request.AddParameter("multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW", "------
WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data;
name=\"\"\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);