简体   繁体   中英

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:

I'm writing Yahoo Messanger client that require as content type, and when I set: 作为内容类型,当我设置时:

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

No POST data send, returned from Yahoo:

UPDATE

I was try to send this 2 values via POST method: presenceState & status .

As stated in Yahoo Messager IM API supported content-type are application/json . And in my code, if I set content-type to application/json , HttpWebRequest didn't send those 2 values via 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

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.

using javascript & jQuery, i sent a simple empty object string in the POST body, and that works:

    $.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:

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. And then you go ahead and overwrite them. This could happen to any header you set like that before you add a bunch of custom ones. If this is what you're doing, just set the custom headers first, and then write to the.Whichever headers.

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. 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.

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

I hope you resolve this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM