简体   繁体   中英

Send form-data using HttpClient C#

I'm trying to make an API call to third party URL, which is working fine through postman, but same request through C# HttpClient not working.

This is how I'm sending request in postman

在此处输入图像描述

C# Sample Code

 var nvc = new List<KeyValuePair<string, string>>();
 nvc.Add(new KeyValuePair<string, string>("PARAM1", "PARAM1 Value"));
 nvc.Add(new KeyValuePair<string, string>("PARAM2", "PARAM2 Value"));
 nvc.Add(new KeyValuePair<string, string>("PARAM3", "PARAM3 Value"));
  var req = new HttpRequestMessage(HttpMethod.Post, "Https://ThirdPartyURL") { 
                Content = new FormUrlEncodedContent(nvc) 
            };

Am I doing anything wrong here?

UPDATE #1: **

Fiddler Traces for postman request(which is working fine)

在此处输入图像描述

Fiddler Traces for C# Request(which is failing) 在此处输入图像描述

Thanks in advance!

Regards, Moksh

Instead of

var nvc = new List<KeyValuePair<string, string>>();

try to create a new class:

public class RecipientSender
{
public string Recipient_First_Name {get; set;}
public string Recipient_Last_Name {get; set;}
.....
}

and create httpclientrequest like this:

....
....

var recipientSender=new RecipientSender { Recipient_FirstName=..., }
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(contentType);
var stringData = JsonConvert.SerializeObject(recipientSender);
contentData = new StringContent(stringData, Encoding.UTF8, "application/json");
var httpResponseMessage=client.PostAsync(url, contentData);
.....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM