使用c#请求带有头部和正文的web服务

本文关键字:正文 web 服务 头部 请求 使用 | 更新日期: 2023-09-27 18:08:47

我正在使用GMC从c#向Android手机发送消息。

链接:https://android.googleapis.com/gcm/send

方法:文章头:

Authorization: key=AIzaSyCPNaU7Pn6csAKxXQHJXSprwWjO0JWaFsw
身体:

{
    "registration_ids": [
        "APA91bEzrLAiphAldxy6lSpSO503YaNm7CCng5uLzGRFWw93dwQIKfisdioyTY2Y0AyJrV81DHd8afBvmOi_KWgMcQKLFwCXJR8vLzuu2_nijBBu9kXRmcBDAGdwTMq9PQ5QPRWDcHh3PGFViTs4lC2DysiRLykASvV25ivY7Vwl_EvNZgcnqkmDM"
    ],
    "data": {
        "price": "Nguyễn Anh Quế. hehe"
    }
}

我已经尝试过从web成功,但在c#中我不知道如何做到这一点。

使用c#请求带有头部和正文的web服务

像这样:

string postData = "{ '"registration_ids'": [ '"APA91bEzrLAiphAldxy6lSpSO503YaNm7CCng5uLzGRFWw93dwQIKfisdioyTY2Y0AyJrV81DHd8afBvmOi_KWgMcQKLFwCXJR8vLzuu2_nijBBu9kXRmcBDAGdwTMq9PQ5QPRWDcHh3PGFViTs4lC2DysiRLykASvV25ivY7Vwl_EvNZgcnqkmDM'" ], '"data'": { '"price'": '"Nguyễn Anh Quế. hehe'" } }";
var request = (HttpWebClient)WebClient.Request("https://android.googleapis.com/gcm/send");
request.Method="POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
var response = (HttpWebRequest)request.GetResponse ();
// response contains the response
string postData = "{ '"registration_ids'": [ '"APA91bEzrLAiphAldxy6lSpSO503YaNm7CCng5uLzGRFWw93dwQIKfisdioyTY2Y0AyJrV81DHd8afBvmOi_KWgMcQKLFwCXJR8vLzuu2_nijBBu9kXRmcBDAGdwTMq9PQ5QPRWDcHh3PGFViTs4lC2DysiRLykASvV25ivY7Vwl_EvNZgcnqkmDM'" ], '"data'": { '"price'": '"Nguyễn Anh Quế. hehe'" } }";
        var request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        request.Method = "POST";
        request.Headers.Add("Authorization: key=AIzaSyCPNaU7Pn6csAKxXQHJXSprwWjO0JWaFsw");
        request.ContentType = "application/json";
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = byteArray.Length;
        Stream dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        var response = request.GetResponse();