7
HttpWebRequest 请求 = (HttpWebRequest) HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

从 Yahoo 返回 POST 数据(我使用 Fiddler 检查):

{"error":{"code":-1003,"detail":"不支持的内容类型错误","description":"不支持的内容类型错误"},"code":-1003}

我正在编写需要application/json 的 Yahoo Messanger 客户端;charset=utf-8作为内容类型,当我设置时:

request.ContentType = "应用程序/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 发送这两个值。

4

5 回答 5

3

看看下面的例子

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();
    }
}
于 2012-08-18T09:00:32.547 回答
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。然后你继续覆盖它们。在添加一堆自定义标题之前,您设置的任何标题都可能发生这种情况。如果这是您正在做的事情,只需先设置自定义标头,然后写入 .Whichever 标头。

于 2018-05-10T00:24:47.967 回答
0

根据您的错误,第一个错误是因为请求的内容类型与 Yahoo 所期望的不匹配。这是有道理的,您的第二个示例正朝着正确的方向发展,但根据您的发布,您似乎得到了回应。使用提琴手,您应该能够将您的帖子与通过网站发出的正确请求进行比较。这可能有助于查明哪里出了问题。

但是无论如何,我们都需要更多地了解您在做什么,因为没有任何内容显示您的帖子内容供我们审查。

于 2011-06-13T05:37:05.763 回答
0

我正在努力解决完全相同的问题。如文档 ( http://developer.yahoo.com/messenger/guide/ch01s04.html ) 中所述,您需要在 POST 请求中有一个空正文 ({})。

使用 javascript & jQuery,我在 POST 正文中发送了一个简单的空对象字符串,并且有效:

    $.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)')
        }});

希望有帮助。

于 2012-09-19T06:42:01.510 回答
-1

我的错误可能与您的错误相同。该问题通过将类型更改presenceState为 int 类型而不是字符串类型来解决。

ClassLogon objLogon = new ClassLogon
  {
    presenceState = ***0***,
    presenceMessage = "I am logn"
  };

我希望你解决这个问题。

于 2011-06-22T18:15:35.900 回答