通过HTTPS POST将JSON,multipart / form-data发送到url(C#)

时间:2018-04-03 05:11:46

标签: c# asp.net json http-post

我想通过HTTPS POST将JSON,多部分数据发送到C#中的webservice-url。

JSON:

info  = {
  fullname:"Name sername",
  code:"123465",
  code2:"12346",
  code3:"1234567"
}

如何将其发送到C#的网址?

2 个答案:

答案 0 :(得分:0)

试试这个有效。

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);

答案 1 :(得分:-1)

这是 示例

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; }
}

注意

  1. HttpClient类可以在System.Net.Http namespace
  2. 下找到
  3. asp.net网络表单中使用RegisterAsyncTask来触发async方法。有关详细信息,请参阅here