如何从WCF REST服务调用URL

本文关键字:服务 调用 URL REST WCF | 更新日期: 2023-09-27 18:21:20

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

如何从WCF REST服务调用URL

查看HttpWebRequest

正如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;
    }

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