从 mvc 调用其余 api post
calling the rest api post from mvc
我想 post RESTful 服务的名称 url 是
“https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991”
完整列表 API 出现在“https://developers.pipedrive.com/v1”
中
以下是我的代码
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();
我遇到错误
The remote server returned an error: (400) Bad Request.
请帮忙
带有名为 "object" 的键的包装器对象对我来说看起来无关紧要。你应该 post 只是内部对象。
下面是我发布到外部 API 的常用策略,希望对您有所帮助
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);
}
也可以等待request
,而不是直接调用.Result
。
要使用此方法,您需要根据响应 json 结构创建一个 C# 模型。我经常使用 http://json2csharp.com/,提供来自我感兴趣的端点的典型 json 响应,然后自动为我生成 c# 模型。
我想 post RESTful 服务的名称 url 是
“https://api.pipedrive.com/v1/persons?api_token=tS5adsXC6V2nH991”
完整列表 API 出现在“https://developers.pipedrive.com/v1”
以下是我的代码
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();
我遇到错误
The remote server returned an error: (400) Bad Request.
请帮忙
带有名为 "object" 的键的包装器对象对我来说看起来无关紧要。你应该 post 只是内部对象。
下面是我发布到外部 API 的常用策略,希望对您有所帮助
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);
}
也可以等待request
,而不是直接调用.Result
。
要使用此方法,您需要根据响应 json 结构创建一个 C# 模型。我经常使用 http://json2csharp.com/,提供来自我感兴趣的端点的典型 json 响应,然后自动为我生成 c# 模型。