I want to post the RESTful service from the name of the url is
"https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991"
list of complete API is present in "https://developers.pipedrive.com/v1"
Following is my code
string URL = "https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991";
string DATA = @"{""object"":{""name"":""rohit sukhla""}}";
var dataToSend = Encoding.UTF8.GetBytes(DATA);
//Passyour service url to the create method
var req =
HttpWebRequest.Create(URL);
req.ContentType = "application/json";
req.ContentLength = dataToSend.Length;
req.Method = "POST";
req.GetRequestStream().Write(dataToSend, 0, dataToSend.Length);
var response1 = req.GetResponse();
I am getting the error
The remote server returned an error: (400) Bad Request.
please help
答案 0 :(得分:2)
Here's my usual strategy for posting to external APIs, I hope it helps
using (var http = new HttpClient()) {
// Define authorization headers here, if any
// http.DefaultRequestHeaders.Add("Authorization", authorizationHeaderValue);
var data = new ModelType {
name = nameValue,
email = emailValue
};
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = http.PostAsync("[api url here]", content);
var response = request.Result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<ResponseModelType>(response);
}
The request
can also be awaited, instead of calling .Result
directly.
To use this approach you need to create a c# model based on the response json structure. Oftentimes I use http://json2csharp.com/, provide a typical json response from the endpoint I'm interested in, and the c# model gets generated for me automatically.
答案 1 :(得分:0)
The wrapper object with a key called "object" looks extraneous to me. You should probably post just the inner object.