Android C2DM 可与基于 java 的 Web 服务配合使用,但如果我尝试使用基于 WS dotNet 的 Web 服务,则会出现 401 错误

发布于 2024-12-29 19:16:02 字数 7462 浏览 1 评论 0 原文

我用 Java 做了一个简单的 Web 服务,并将其部署在 JBOSS 5.1 中。 该 WS 处理 C2DM 服务,用于向 Android 手机发送通知消息。我在 google c2dm api 中将所有内容设置为红色,首先,我注册访问 c2dm 服务。在这种情况下,一切正常。

现在我必须在 IIS7 上的 .NET 中执行相同的操作。关于 .Net 代码的一些说明:

  • setRegId() 和 PushMessage() 方法可通过 WebService 获得。

  • 在设置字符串“reg_id”和“device_id”后,setRegId() 会简单地调用

  • < p>所有注释的代码都是我解决问题的尝试,但都没有用

这就是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace WebService1
{

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]

public class Service1 : System.Web.Services.WebService
{

    private String accountType = "HOSTED_OR_GOOGLE";
    private String email = "[email protected]";
    private String password = "password";
    private String service = "ac2dm";
    private String source = "com.cloudTest.app";
    private String HTTPHeaderCT = "application/x-www-form-urlencoded";

    private String auth;
    private String reg_Id;
    private String deviceId;
    private String collapseKey = "CollapseKey";

    public void handShakeRegId()
    {

        HttpWebRequest req;
        Stream reqst;
        try
        {
            req = (HttpWebRequest)WebRequest.Create(@"https://www.google.com/accounts/ClientLogin");

         //   string proxy = null;
         //   req.MaximumAutomaticRedirections = 4;
         //   req.MaximumResponseHeadersLength = 4;
         //   req.Credentials = CredentialCache.DefaultCredentials;
            string data = String.Format("accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}", accountType, email, password, service, source);

            byte[] buffer = Encoding.UTF8.GetBytes(data);
         //   ASCIIEncoding encoding = new ASCIIEncoding();
         //   byte[] buffer = encoding.GetBytes(data);

            req.Method = "POST";
            req.ContentType = HTTPHeaderCT;
            req.ContentLength = buffer.Length;
          //  req.Proxy = new WebProxy(proxy, true);
          //  req.CookieContainer = new CookieContainer();

            reqst = req.GetRequestStream(); // add form data to request stream
            reqst.Write(buffer, 0, buffer.Length);

        }
        catch (Exception e)
        {
            Debug.WriteLine("--------------------");
            Debug.Write("(handShakeRegId) Request Error:" + e);
            Debug.WriteLine("--------------------");
            throw;
        }

        HttpWebResponse res;
        Stream resst;
        try
        {
            res = (HttpWebResponse)req.GetResponse();

            resst = res.GetResponseStream();
            StreamReader sr = new StreamReader(resst, Encoding.UTF8);
            string response = sr.ReadToEnd();

            string SID = response.Substring((response.IndexOf("SID=") + 4),
            (response.IndexOf("\n") - 4));//extracting SID

            string Auth = response.Substring((response.IndexOf("Auth=") + 5),
            (response.Length - (response.IndexOf("Auth=") + 5)) - 1);//extracting Auth

            auth = Auth;
        }
        catch (Exception e)
        {
            Debug.Write("(handShakeRegId) Response Error:" + e);
            throw;
        }

        resst.Flush();
        resst.Close();
        reqst.Flush();
        reqst.Close();
    }

    [WebMethod]
    public void setRegId(String reg_id, String device_id)
    {

        reg_Id = reg_id;
        deviceId = device_id;

        Debug.WriteLine("RegID=" + reg_Id);
        Debug.WriteLine("--------------------");
        Debug.WriteLine("DeviceID=" + deviceId);

        handShakeRegId();
    }

    [WebMethod]
    public void pushMessage(String msg)
    {
        // Needed! Without an SSL Exception comes out
        System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };

        HttpWebRequest req;
        Stream reqst;

        try
        {

            req = (HttpWebRequest)WebRequest.Create("http://android.apis.google.com/c2dm/send");
            //req.MaximumAutomaticRedirections = 4;
            //req.MaximumResponseHeadersLength = 4;
            //req.Credentials = CredentialCache.DefaultCredentials;
            //req.Credentials = new NetworkCredential("[email protected]","password");
            //req.KeepAlive = true;

            //string proxy = null;


            string data = String.Format("registration_id={0}&collapse_key={1}&data.message={2}", reg_Id, collapseKey, msg);

           // ASCIIEncoding encoding = new ASCIIEncoding();
           // byte[] buffer = encoding.GetBytes(data);

            byte[] buffer = Encoding.UTF8.GetBytes(data);

            req.Method = "POST";
            req.ContentType = HTTPHeaderCT;
            req.ContentLength = buffer.Length;
            req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);

           // req.Proxy = new WebProxy(proxy, true);
           // req.CookieContainer = new CookieContainer();

            reqst = req.GetRequestStream(); // add form data to request stream
            reqst.Write(buffer, 0, buffer.Length);
        }
        catch (Exception e)
        {
            Debug.Write("(PushMessageMsgOUT)Error: " + e);
            throw;
        }

        HttpWebResponse res;
        Stream resst;

        try
        {
            res = (HttpWebResponse)req.GetResponse();

            HttpStatusCode responseCode = ((HttpWebResponse)res).StatusCode;
            if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
            {
                Debug.WriteLine("Unauthorized - need new token");
            }
            else if (!responseCode.Equals(HttpStatusCode.OK))
            {
                Debug.WriteLine("Response from web service not OK :");
                Debug.WriteLine(((HttpWebResponse)res).StatusDescription);
            }

            resst = res.GetResponseStream();
            StreamReader sr = new StreamReader(resst);

            string response = sr.ReadToEnd();

        }
        catch (Exception e)
        {
            Debug.WriteLine("(pushMessageMsgIN) Error: "+e);
            throw;
        }

        resst.Flush();
        resst.Close();
        reqst.Flush();
        reqst.Close();
    }
  }
}
  • 握手方法有效 出色地!我毫无问题地获得了身份验证令牌。
  • setRegId方法由Android设备调用(在我的例子中是Android+GoogleApi 2.2模拟器)

在pushMessage getResponse()中出现的错误总是相同的(这很奇怪,因为我实现的连接与握手方法中的连接完全相同:-/) :

System.dll 中发生了“System.Net.WebException”类型的第一次机会异常 (pushMessageMsgIN) 错误:System.Net.WebException:远程服务器错误 (401) 在 System.Net.HttpWebRequest.GetResponse() 中未经授权

2 天搜索有用的内容,但是......没有! 压力很大...

我希望有人能帮助我。

我在 IIS 中红色了有关身份验证的内容,因此我启用了匿名用户和其他未知的内容只是为了尝试。没有什么!

i did a simple Web Service in Java and i deployed it in JBOSS 5.1.
This WS handles C2DM service for sending a notify message to an Android phone. I set all like i red in google c2dm api, and, first of all, i sign up for accessing to c2dm service. In this case, all works well.

Now i have to do the same in .NET on IIS7. Some clarification about the .Net code:

  • setRegId() and pushMessage() method are available by WebService.

  • handShakeRegId() is simply called by setRegId() after String "reg_id" and "device_id" are setted

  • all code commented are my try for solving problem, but all was useless

Thats the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace WebService1
{

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]

public class Service1 : System.Web.Services.WebService
{

    private String accountType = "HOSTED_OR_GOOGLE";
    private String email = "[email protected]";
    private String password = "password";
    private String service = "ac2dm";
    private String source = "com.cloudTest.app";
    private String HTTPHeaderCT = "application/x-www-form-urlencoded";

    private String auth;
    private String reg_Id;
    private String deviceId;
    private String collapseKey = "CollapseKey";

    public void handShakeRegId()
    {

        HttpWebRequest req;
        Stream reqst;
        try
        {
            req = (HttpWebRequest)WebRequest.Create(@"https://www.google.com/accounts/ClientLogin");

         //   string proxy = null;
         //   req.MaximumAutomaticRedirections = 4;
         //   req.MaximumResponseHeadersLength = 4;
         //   req.Credentials = CredentialCache.DefaultCredentials;
            string data = String.Format("accountType={0}&Email={1}&Passwd={2}&service={3}&source={4}", accountType, email, password, service, source);

            byte[] buffer = Encoding.UTF8.GetBytes(data);
         //   ASCIIEncoding encoding = new ASCIIEncoding();
         //   byte[] buffer = encoding.GetBytes(data);

            req.Method = "POST";
            req.ContentType = HTTPHeaderCT;
            req.ContentLength = buffer.Length;
          //  req.Proxy = new WebProxy(proxy, true);
          //  req.CookieContainer = new CookieContainer();

            reqst = req.GetRequestStream(); // add form data to request stream
            reqst.Write(buffer, 0, buffer.Length);

        }
        catch (Exception e)
        {
            Debug.WriteLine("--------------------");
            Debug.Write("(handShakeRegId) Request Error:" + e);
            Debug.WriteLine("--------------------");
            throw;
        }

        HttpWebResponse res;
        Stream resst;
        try
        {
            res = (HttpWebResponse)req.GetResponse();

            resst = res.GetResponseStream();
            StreamReader sr = new StreamReader(resst, Encoding.UTF8);
            string response = sr.ReadToEnd();

            string SID = response.Substring((response.IndexOf("SID=") + 4),
            (response.IndexOf("\n") - 4));//extracting SID

            string Auth = response.Substring((response.IndexOf("Auth=") + 5),
            (response.Length - (response.IndexOf("Auth=") + 5)) - 1);//extracting Auth

            auth = Auth;
        }
        catch (Exception e)
        {
            Debug.Write("(handShakeRegId) Response Error:" + e);
            throw;
        }

        resst.Flush();
        resst.Close();
        reqst.Flush();
        reqst.Close();
    }

    [WebMethod]
    public void setRegId(String reg_id, String device_id)
    {

        reg_Id = reg_id;
        deviceId = device_id;

        Debug.WriteLine("RegID=" + reg_Id);
        Debug.WriteLine("--------------------");
        Debug.WriteLine("DeviceID=" + deviceId);

        handShakeRegId();
    }

    [WebMethod]
    public void pushMessage(String msg)
    {
        // Needed! Without an SSL Exception comes out
        System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate(object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };

        HttpWebRequest req;
        Stream reqst;

        try
        {

            req = (HttpWebRequest)WebRequest.Create("http://android.apis.google.com/c2dm/send");
            //req.MaximumAutomaticRedirections = 4;
            //req.MaximumResponseHeadersLength = 4;
            //req.Credentials = CredentialCache.DefaultCredentials;
            //req.Credentials = new NetworkCredential("[email protected]","password");
            //req.KeepAlive = true;

            //string proxy = null;


            string data = String.Format("registration_id={0}&collapse_key={1}&data.message={2}", reg_Id, collapseKey, msg);

           // ASCIIEncoding encoding = new ASCIIEncoding();
           // byte[] buffer = encoding.GetBytes(data);

            byte[] buffer = Encoding.UTF8.GetBytes(data);

            req.Method = "POST";
            req.ContentType = HTTPHeaderCT;
            req.ContentLength = buffer.Length;
            req.Headers.Add("Authorization", "GoogleLogin auth=" + auth);

           // req.Proxy = new WebProxy(proxy, true);
           // req.CookieContainer = new CookieContainer();

            reqst = req.GetRequestStream(); // add form data to request stream
            reqst.Write(buffer, 0, buffer.Length);
        }
        catch (Exception e)
        {
            Debug.Write("(PushMessageMsgOUT)Error: " + e);
            throw;
        }

        HttpWebResponse res;
        Stream resst;

        try
        {
            res = (HttpWebResponse)req.GetResponse();

            HttpStatusCode responseCode = ((HttpWebResponse)res).StatusCode;
            if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
            {
                Debug.WriteLine("Unauthorized - need new token");
            }
            else if (!responseCode.Equals(HttpStatusCode.OK))
            {
                Debug.WriteLine("Response from web service not OK :");
                Debug.WriteLine(((HttpWebResponse)res).StatusDescription);
            }

            resst = res.GetResponseStream();
            StreamReader sr = new StreamReader(resst);

            string response = sr.ReadToEnd();

        }
        catch (Exception e)
        {
            Debug.WriteLine("(pushMessageMsgIN) Error: "+e);
            throw;
        }

        resst.Flush();
        resst.Close();
        reqst.Flush();
        reqst.Close();
    }
  }
}
  • Handshake method works well! I get auth token without problem.
  • setRegId method is called by Android device (in my case is the Android+GoogleApi 2.2 emulator)

Error which comes out is always the same in pushMessage getResponse() ( and its strange because i implement connection exactly like its in handshake method :-/ ):

A first chance exception of type 'System.Net.WebException' occurred in System.dll
(pushMessageMsgIN) Error: System.Net.WebException: remote server error (401) Unauthorized in System.Net.HttpWebRequest.GetResponse()

2 days for searching something useful but.... NOTHING!!
Its very stressful...

I hope someone can help me.

I red something about Authentication in IIS, so i enabled Anonymous User and other unknown things just for trying. Nothing!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慕烟庭风 2025-01-05 19:16:02

解决了:我的愚蠢!我在私有字符串源中犯了一个错误!我指定了错误的包名! -.-

Solved: MY STUPIDITY !!! i made a mistake in private String source !! I specified a wrong package name! -.-

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文