[英]post JSON from HttpClient to web API in C#
[英]JSON Post from C# to a ColdFusion API
我正在嘗試連接到需要JSON的API,並且不斷收到500個內部錯誤。 再次閱讀連接說明后,看來我的問題源於以下事實:我傳遞了一個字符串,而API正在尋找以字符串作為值的表單字段。 如何在C#中以編程方式完成? 以下不適用於我。
//Create JSON string to send to iCohere API using POST
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.api,url");
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
ClientID = ConfigurationManager.AppSettings["ClientID"],
AuthCode = ConfigurationManager.AppSettings["AuthCode"],
cSeq = ConfigurationManager.AppSettings["cSeq"],
LastName = "Fett",
FirstName = "Bubba",
EmailAddress = "dec18@comingsoon.com",
EventCode = "WEBINAR"
});
TextBox iCohereForm = new TextBox();
iCohereForm.ID = "JSONAPISTR";
iCohereForm.Text = json;
streamWriter.Write(iCohereForm);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
更新:此問題的適當位置是代碼審查
問題是您試圖將UI控件對象放入StreamWriter中。 並在發出HTTP請求期間使用此內存流數據。
另外,您正在以錯誤的方式執行HTTP請求。 正確的是:
string json = new JavaScriptSerializer().Serialize(new
{
ClientID = ConfigurationManager.AppSettings["ClientID"],
AuthCode = ConfigurationManager.AppSettings["AuthCode"],
cSeq = ConfigurationManager.AppSettings["cSeq"],
LastName = "Fett",
FirstName = "Bubba",
EmailAddress = "dec18@comingsoon.com",
EventCode = "WEBINAR"
});
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api url");
requst.Method = "POST";
requst.ContentType = "application/json";
byte[] _byteVersion = Encoding.ASCII.GetBytes(json);
request.ContentLength = _byteVersion.Length
Stream stream = request.GetRequestStream();
stream.Write(_byteVersion, 0, _byteVersion.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.