简单的C#RESTfull客户端

时间:2016-06-09 21:01:25

标签: c# .net xml rest client

我正在尝试使用尽可能简单的C#实用程序来使用RESTful服务。响应以XML格式给出,我只想将其放入字符串中,然后再将其打印出来#34;并将其保存在磁盘上。现在我正在努力获得适当的回应。服务是第三方,它工作正常,在浏览器和Java客户端多次测试。在C#实用程序中,授权是正常的,据我所知,我在调试器中看到了响应对象

  

StatusCode OK System.Net.HttpStatusCode

  

StatusDescription" OK"串

但看起来响应本身是空的?必须以String形式保存响应的字符串Xml为空(不为空但为空)。我做错了什么?

这是完整的代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Xml;

namespace ConsoleApplication3
{
    class Program
    {

        public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
        {
            string authInfo = userName + ":" + userPassword;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Headers["Authorization"] = "Basic " + authInfo;
        }

        static void Main(string[] args)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            String Xml;

            // Create the web request  
            request = WebRequest.Create("https://some.web.services.com?id='1234'&param1='1'&param2='2'") as HttpWebRequest;
            SetBasicAuthHeader(request, "userName", "userPassword");

            // Get response
            response = request.GetResponse() as HttpWebResponse;

            // Get the response stream  
            StreamReader reader = new StreamReader(response.GetResponseStream());

            Xml = reader.ReadToEnd();

            // Console xml output  
            Console.WriteLine(Xml); //see if we get the xml response
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我通过手动使用Authorization标头看到了一些奇怪的行为;试试这个:

    using System.Net; // contains HttpRequestHeader enum

    public static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
    {
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
        string authHeader = string.Format("Basic {0}", authInfo);
        request.Headers[HttpRequestHeader.Authorization] = authHeader;
    }

答案 1 :(得分:1)

我建议你使用HttpClient你要做的事情,你的代码应该是这样的:

static void Main(...)
{
    var token = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{user}:{pwd}"));
    using(var client = new HttpClient())
    {
        client.DefaultHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);

        // here you could also use await right after GetAsync but since a Console application I use this instead
        var response = client.GetAsync(url).GetAwaiter().GetResult();

        // again the await could help here
        var xml = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();

        Console.WriteLine(xml);
    }
}

你也可以通过调用Stream来获得string而不是response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();,并从那里使用它,如果你想要读取块或缓冲到优化

希望这会有所帮助。另请查看this它可能很有用,因为它包含几个扩展,可以在REST中使用的流行格式之间进行转换,虽然我不确定它是否可以帮助您以及xml