C# 中的 Codemetric 优化 httpwebrequest

发布于 2024-10-08 22:35:00 字数 822 浏览 2 评论 0原文

问题是我的 C# 程序中的 httpwebrequest 方法。 Visual Studio 给它的度量为 60,这相当蹩脚..那么我怎样才能更有效地对其进行编程呢? (:

我的实际代码:

public string httpRequest(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Proxy = WebRequest.DefaultWebProxy;
        request.MediaType = "HTTP/1.1";
        request.ContentType = "text/xml";
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using(StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                String sresp = streamr.ReadToEnd();
        return sresp;
    }

感谢您的帮助。;)

the problem is the httpwebrequest method in my c# program. visual studio gives it a metric of 60, thats pretty lame.. so how can i program it more efficient? (:

my actual code:

public string httpRequest(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Proxy = WebRequest.DefaultWebProxy;
        request.MediaType = "HTTP/1.1";
        request.ContentType = "text/xml";
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using(StreamReader streamr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                String sresp = streamr.ReadToEnd();
        return sresp;
    }

thanks for helping. ;)

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

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

发布评论

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

评论(2

琴流音 2024-10-15 22:35:00

好吧,首先我不会让数字统治我的代码:)

但是,使用 WebClient 可能会大大简化事情 - 需要计算的代码更少。我不在电脑前,但这看起来像是一个 DownloadString 调用,加上一些请求标头。

http://msdn.microsoft.com/en- us/library/fhd1f0sw(v=VS.100).aspx

哦,在您创建的所有 IDisposable 对象周围添加一些 using 语句。

Well, firstly I wouldnt let a number rule my code :)

However, using WebClient may simplify things quite a bit - less code to be counted. I'm not at a PC but that looks like a single DownloadString call, plus a few request headers.

http://msdn.microsoft.com/en-us/library/fhd1f0sw(v=VS.100).aspx

Oh, and add some using statements around all the IDisposable objects you create.

红ご颜醉 2024-10-15 22:35:00

以下是我在构建的社交网络类中使用的代码,该类与 Twitter、Facebook、Tumblr 等进行交互。根据您的需要进行修改。另外,我不知道 VS 会给出什么“指标”,但如果您指的是“计算代码指标”,60 仍然不错。 20 到 100 被认为是易于维护的,所以我不会担心太多了。

protected string Request(
    string Method,
    Uri Endpoint,
    string[][] Headers,
    string Params) {
    try {
        ServicePointManager.Expect100Continue = false;

        HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Endpoint);

        Request.Method = Method;

        if (Method == "POST") {
            Request.ContentLength = Params.Length;
            Request.ContentType = "application/x-www-form-urlencoded";
        };

        for (byte a = 0, b = (byte)Headers.Length; a < b; a++) {
            Request.Headers.Add(Headers[a][0], Headers[a][1]);
        };

        if (!String.IsNullOrWhiteSpace(Params)) {
            using (StreamWriter Writer = new StreamWriter(Request.GetRequestStream())) {
                Writer.Write(Params);
            };
        };

        HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

        Request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointDelegate);

        using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) {
            string R = Reader.ReadToEnd();

            try {
                Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
            } catch (Exception) {
                Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
            };

            return (R);
        };
    } catch (WebException Ex) {
        try {
            if (Ex.Status != WebExceptionStatus.Success) {
                using (StreamReader Reader = new StreamReader(Ex.Response.GetResponseStream())) {
                    string R = Reader.ReadToEnd();

                    try {
                        Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
                    } catch (Exception) {
                        Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
                    };

                    return (R);
                };
            };
        } catch (Exception) {
            //  Ignore
        };

        return (string.Empty);
    } catch (Exception) {
        return (string.Empty);
    };
}

private IPEndPoint BindIPEndPointDelegate(
    ServicePoint ServicePoint,
    IPEndPoint RemoteEndPoint,
    int Retries) {
    if (String.IsNullOrWhiteSpace(this.IPEndpoint)) {
        return new IPEndPoint(IPAddress.Any, 5000);
    } else {
        return new IPEndPoint(IPAddress.Parse(this.IPEndpoint), 5000);
    };
}

Here's the code I use in a social networking class I built which interacts with Twitter, Facebook, Tumblr, etc. Modify as you see fit. Also, I don't know what "metric" it would be given by VS, but if you're referring to the "Calculate Code Metrics" a 60 is still good. 20 to 100 is considered to be well maintainable, so I wouldn't worry too much.

protected string Request(
    string Method,
    Uri Endpoint,
    string[][] Headers,
    string Params) {
    try {
        ServicePointManager.Expect100Continue = false;

        HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Endpoint);

        Request.Method = Method;

        if (Method == "POST") {
            Request.ContentLength = Params.Length;
            Request.ContentType = "application/x-www-form-urlencoded";
        };

        for (byte a = 0, b = (byte)Headers.Length; a < b; a++) {
            Request.Headers.Add(Headers[a][0], Headers[a][1]);
        };

        if (!String.IsNullOrWhiteSpace(Params)) {
            using (StreamWriter Writer = new StreamWriter(Request.GetRequestStream())) {
                Writer.Write(Params);
            };
        };

        HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();

        Request.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointDelegate);

        using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) {
            string R = Reader.ReadToEnd();

            try {
                Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
            } catch (Exception) {
                Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
            };

            return (R);
        };
    } catch (WebException Ex) {
        try {
            if (Ex.Status != WebExceptionStatus.Success) {
                using (StreamReader Reader = new StreamReader(Ex.Response.GetResponseStream())) {
                    string R = Reader.ReadToEnd();

                    try {
                        Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Headers[0][1] + "</p><p>" + Params + "</p><p>" + R + "</p>");
                    } catch (Exception) {
                        Mailer.Notification("<p>" + Endpoint.AbsoluteUri + "</p><p>" + Params + "</p><p>" + R + "</p>");
                    };

                    return (R);
                };
            };
        } catch (Exception) {
            //  Ignore
        };

        return (string.Empty);
    } catch (Exception) {
        return (string.Empty);
    };
}

private IPEndPoint BindIPEndPointDelegate(
    ServicePoint ServicePoint,
    IPEndPoint RemoteEndPoint,
    int Retries) {
    if (String.IsNullOrWhiteSpace(this.IPEndpoint)) {
        return new IPEndPoint(IPAddress.Any, 5000);
    } else {
        return new IPEndPoint(IPAddress.Parse(this.IPEndpoint), 5000);
    };
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文