0

I want to send JSON, multipart-data via HTTPS POST to webservice-url in C#.

JSON:

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

How to send it to url in C#?

Jeric Cruz
  • 1,899
  • 1
  • 14
  • 29
Doston
  • 21
  • 1
  • 3

2 Answers2

0

Here is an example.

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

Here in the above example, there is a class Info, which can be defined as follows.

public class Info
{
   public String fullname { get; set; }
   public String code { get; set; }
   public String code2 { get; set; }
   public String code3 { get; set; }
}

Note:

  1. HttpClient class can be found under System.Net.Http namespace
  2. Use RegisterAsyncTask in your asp.net web form to trigger the async method. see here for more details.
Christlin Panneer
  • 1,599
  • 2
  • 19
  • 31
-1

Try this one it works.

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