![](/img/trans.png)
[英]How to read HTTP Post data with content-type of application/json in C# 4.0
[英]HttpWebRequest, How to Send POST Data with Application/JSON Content-Type?
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
从雅虎返回的 POST 数据已发送(我使用 Fiddler 检查):
{"error":{"code":-1003,"detail":"不支持的内容类型错误","description":"不支持的内容类型错误"},"code":-1003}
我正在编写需要application/json 的 Yahoo Messanger 客户端; charset=utf-8作为内容类型,当我设置时:
request.ContentType = "application/json; charset=utf-8";
没有 POST 数据发送,从 Yahoo 返回:
{"error":{"code":-1005,"detail":"无效参数错误","description":"无效参数错误"},"code":-1005}
更新
我试图通过 POST 方法发送这 2 个值: presenceState & status 。
如Yahoo Messager IM API中所述,支持的内容类型为application/json 。 在我的代码中,如果我将content-type设置为application/json ,则HttpWebRequest不会通过 POST 发送这两个值。
看看下面的例子
byte[] data = CreateData(value);
var requst = (HttpWebRequest) WebRequest.Create(uri);
requst.Method = "POST";
requst.ContentType = "application/json";
requst.ContentLength = data.Length;
using (Stream stream = requst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
CreateData 在哪里
public static byte[] Create<T>(T value)
{
var serializer = new DataContractJsonSerializer(typeof (T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, value);
return stream.ToArray();
}
}
我正在努力解决完全相同的问题。 如文档 ( http://developer.yahoo.com/messenger/guide/ch01s04.html ) 中所述,您需要在 POST 请求中有一个空正文 ({})。
使用 javascript 和 jQuery,我在 POST 正文中发送了一个简单的空 object 字符串,并且有效:
$.ajax({
type: 'POST',
url: 'http://developer.messenger.yahooapis.com/v1/session',
data: JSON.stringify({ }),
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', OAuth.getAuthorizationHeader("yahooapis.com", message.parameters));
xhr.setRequestHeader('Content-Type','application/json; charset=UTF-8');
xhr.setRequestHeader('X-Yahoo-Msgr-User-Agent','YahooMessenger/1.0 (yourapp; 1.0.0.1)')
}});
希望有帮助。
我参加聚会超级迟到了,但我最终来到这里试图弄清楚我在搞砸什么,所以也许这会对其他人有所帮助。
如果在您的 c# 代码中设置您的内容类型,然后添加一些其他标题 - 如下所示:
httpWebRequest.ContentType = @"application/json; charset=utf-8";
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer "+oAuthBearerToken);
httpWebRequest.Headers = headers;
实际发生的情况是,当您写入.ContentType 时,它会在您的请求的 WebHeaderCollection 中设置 Content-Type。 然后你提前 go 并覆盖它们。 在添加一堆自定义之前,您设置的任何 header 都可能发生这种情况。 如果这是您正在做的,只需先设置自定义标题,然后写入.Whichever 标题。
根据您的错误,第一个错误是因为请求的内容类型与 Yahoo 所期望的不匹配。 这是有道理的,您的第二个示例正朝着正确的方向发展,但根据您的发布,您似乎得到了回应。 使用提琴手,您应该能够将您的帖子与通过网站发出的正确请求进行比较。 这可能有助于查明哪里出了问题。
但是无论如何,我们都需要更多地了解您在做什么,因为没有任何内容显示您的帖子内容供我们审查。
我的错误可能与您的错误相同。 通过将presenceState
的类型更改为 int 类型而不是 string 类型来解决问题。
ClassLogon objLogon = new ClassLogon
{
presenceState = ***0***,
presenceMessage = "I am logn"
};
我希望你解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.