简体   繁体   English

HttpWebRequest,如何使用 Application/JSON Content-Type 发送 POST 数据?

[英]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 data was send (I check using Fiddler) returned from Yahoo:从雅虎返回的 POST 数据已发送(我使用 Fiddler 检查):

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

I'm writing Yahoo Messanger client that require application/json;我正在编写需要application/json 的 Yahoo Messanger 客户端; charset=utf-8 as content type, and when I set: charset=utf-8作为内容类型,当我设置时:

request.ContentType = "application/json; charset=utf-8";

No POST data send, returned from Yahoo:没有 POST 数据发送,从 Yahoo 返回:

{"error":{"code":-1005,"detail":"Invalid Argument Error","description":"Invalid Argument Error"},"code":-1005} {"error":{"code":-1005,"detail":"无效参数错误","description":"无效参数错误"},"code":-1005}

UPDATE更新

I was try to send this 2 values via POST method: presenceState & status .我试图通过 POST 方法发送这 2 个值: presenceState & status

As stated in Yahoo Messager IM API supported content-type are application/json .Yahoo Messager IM API中所述,支持的内容类型application/json And in my code, if I set content-type to application/json , HttpWebRequest didn't send those 2 values via POST.在我的代码中,如果我将content-type设置为application/json ,则HttpWebRequest不会通过 POST 发送这两个值。

Take a look on following example看看下面的例子

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);
}

Where CreateData is 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();
    }
}

i was struggling with the exact same issue.我正在努力解决完全相同的问题。 as noted in the documentation ( http://developer.yahoo.com/messenger/guide/ch01s04.html ), you need to have an empty body ({}) in the POST request.如文档 ( http://developer.yahoo.com/messenger/guide/ch01s04.html ) 中所述,您需要在 POST 请求中有一个空正文 ({})。

using javascript & jQuery, i sent a simple empty object string in the POST body, and that works:使用 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)')
        }});

hope that helps.希望有帮助。

I'm super late to the party, but I ended up here trying to figure out what I was messing up, so maybe this will help someone else.我参加聚会超级迟到了,但我最终来到这里试图弄清楚我在搞砸什么,所以也许这会对其他人有所帮助。

If in your c# code you set your content type and then add some other headers-- something like this:如果在您的 c# 代码中设置您的内容类型,然后添加一些其他标题 - 如下所示:

httpWebRequest.ContentType = @"application/json; charset=utf-8";        
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer "+oAuthBearerToken);
httpWebRequest.Headers = headers;

what's actually happening, is that when you write to.ContentType, under the hood it's setting Content-Type in your request's WebHeaderCollection.实际发生的情况是,当您写入.ContentType 时,它会在您的请求的 WebHeaderCollection 中设置 Content-Type。 And then you go ahead and overwrite them.然后你提前 go 并覆盖它们。 This could happen to any header you set like that before you add a bunch of custom ones.在添加一堆自定义之前,您设置的任何 header 都可能发生这种情况。 If this is what you're doing, just set the custom headers first, and then write to the.Whichever headers.如果这是您正在做的,只需先设置自定义标题,然后写入.Whichever 标题。

Based on your error, the first one is failing as the content type of the request doesn't match that of what Yahoo is expecting.根据您的错误,第一个错误是因为请求的内容类型与 Yahoo 所期望的不匹配。 This makes sense and your second example is going towards the right path, but based on your posting it seems you are getting a response.这是有道理的,您的第二个示例正朝着正确的方向发展,但根据您的发布,您似乎得到了回应。 With fiddler you should be able to compare your posting with that of a proper request through the site.使用提琴手,您应该能够将您的帖子与通过网站发出的正确请求进行比较。 That might help pinpoint where it is going wrong.这可能有助于查明哪里出了问题。

But regardless we will need to be seeing a bit more of what you are doing as there is nothing showing hte contents of your post for us to review.但是无论如何,我们都需要更多地了解您在做什么,因为没有任何内容显示您的帖子内容供我们审查。

My error maybe is the same your error.我的错误可能与您的错误相同。 The problem is resolved by change type of presenceState to int type not string type.通过将presenceState的类型更改为 int 类型而不是 string 类型来解决问题。

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

I hope you resolve this.我希望你解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#4.0中读取内容类型为application / json的HTTP Post数据 - How to read HTTP Post data with content-type of application/json in C# 4.0 如何将JSON和图像发布到WCF(使用内容类型:application / JSON) - How to Post a JSON and an Image to WCF (Using Content-type: application/JSON) c# HttpClient post response content-type application/json - c# HttpClient post response content-type application/json 使用内容类型application / x-www-form-urlencoded解析从HTTP POST接收的C#中的JSON数据 - Parsing JSON data in C# received from HTTP POST with content-type application/x-www-form-urlencoded 如何将查询字符串和json数据添加到httpWebRequest类型POST - How to add query string and json data to httpWebRequest type POST 如果Content-Type为“ text / plain”,则GET RestSharp请求返回空值,而如果Content-Type为“ application / json”,则返回数据 - GET RestSharp request returns null value if the Content-Type is “text/plain”, whereas if Content-Type is “application/json” data is returned C#HttpWebRequest内容类型未更改 - C# HttpWebRequest Content-type not Changing 如何使用HttpWebRequest在POST请求中发送数据 - How to send data in a POST request with HttpWebRequest 在 C# 上发送带有内容类型应用程序 Json 的 post Https 请求 - send post Https request with Content Type application Json on C# 类型为“application/x-www-form-urlencoded”的 C# HttpWebRequest - 如何在内容正文中发送“&amp;”字符? - C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM