如何从WCF REST服务调用URL

时间:2012-01-25 17:59:57

标签: c# .net wcf

我有一个WCF REST服务需要调用一个URL(可能是一个网页,REST服务等)并传递一些值(类似http://xyz.com/callback?a=1&b=2)。它不需要担心响应(只是调用并忘记)。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)

正如Matthew所说,HttpWebRequest是通过代码发出Web请求的理想方式。您应该使用像Fiddler这样的工具来捕获网站的流量,然后在代码中重建相同类型的请求。我有一个帮助类,我使用它,但这是我在发送数据和请求时使用的一部分。

    public static string HttpRequest(string requestType, string contentType, string parameters, string URI, CookieContainer cookies)
    {
        string results = string.Empty;

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);

        req.CookieContainer = cookies;
        req.Method = requestType;
        req.AllowAutoRedirect = true;
        req.ContentLength = 0;
        req.ContentType = contentType;
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";

        if (!string.IsNullOrEmpty(parameters))
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
            req.ContentLength = byteArray.Length;
            Stream dataStream = req.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
        }

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

            if (HttpStatusCode.OK == response.StatusCode)
            {
                Stream responseStream = response.GetResponseStream();

                // Content-Length header is not trustable, but makes a good hint.        
                // Responses longer than int size will throw an exception here!        
                int length = (int)response.ContentLength;
                const int bufSizeMax = 65536;

                // max read buffer size conserves memory        
                const int bufSizeMin = 8192;

                // min size prevents numerous small reads        
                // Use Content-Length if between bufSizeMax and bufSizeMin        
                int bufSize = bufSizeMin;
                if (length > bufSize) bufSize = length > bufSizeMax ? bufSizeMax : length;

                // Allocate buffer and StringBuilder for reading response        
                byte[] buf = new byte[bufSize];
                StringBuilder sb = new StringBuilder(bufSize);

                // Read response stream until end        
                while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                    sb.Append(Encoding.UTF8.GetString(buf, 0, length));

                results = sb.ToString();
            }
            else
            {
                results = "Failed Response : " + response.StatusCode;
            }
        }
        catch (Exception exception)
        {
            Log.Error("WebHelper.HttpRequest", exception);
        }

        return results;
    }

注意:可能会对其他助手进行一些调用,但基本流量表会让您了解需要做什么。