通过 HTTPS POST 发送 JSON、多部分/表单数据到 url (C#)

问题描述 投票:0回答:2

我想通过 HTTPS POST 将 JSON 多部分数据发送到

C#
中的 webservice-url。

JSON:

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

如何发送到

C#
中的url?

c# asp.net json http-post
2个回答
0
投票

这是一个示例

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
    命名空间下找到
  2. asp.net Web 表单
    中使用 RegisterAsyncTask 来触发
    async
    方法。请参阅此处了解更多详情。

-1
投票

试试这个,它有效。

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);
© www.soinside.com 2019 - 2024. All rights reserved.