简体   繁体   English

提供了无效的请求 URI。 请求 URI 必须是绝对 URI 或必须设置 BaseAddress。 尝试使用网络服务

[英]An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set. trying to consuming a webservice

I am trying to Consume a Web Service using HttpClient in .NET and after i did all steps mentioned in msdn我正在尝试使用 .NET 中的 HttpClient 来使用 Web 服务,并且在我完成了msdn 中提到的所有步骤之后

o Get the following exception : An invalid request URI was provided. o 获得以下异常:提供了无效的请求 URI。 The request URI must either be an absolute URI or BaseAddress must be set.请求 URI 必须是绝对 URI 或必须设置 BaseAddress。

here is my class这是我的班级

public class Customer
{
    public int id { get; set; }
    public string id_default_group { get; set; }
    public string id_lang { get; set; }
    public string newsletter_date_add { get; set; }
    public string ip_registration_newsletter { get; set; }
    public string last_passwd_gen { get; set; }
    public string secure_key { get; set; }
    public string deleted { get; set; }
    public string passwd { get; set; }
    public string lastname { get; set; }
    public string firstname { get; set; }
    public string email { get; set; }
    public string id_gender { get; set; }
    public string birthday { get; set; }
    public string newsletter { get; set; }
    public string optin { get; set; }
    public string website { get; set; }
    public string company { get; set; }
    public string siret { get; set; }
    public string ape { get; set; }
    public string outstanding_allow_amount { get; set; }
    public string show_public_prices { get; set; }
    public string id_risk { get; set; }
    public string max_payment_days { get; set; }
    public string active { get; set; }
    public string note { get; set; }
    public string is_guest { get; set; }
    public string id_shop { get; set; }
    public string id_shop_group { get; set; }
    public string date_add { get; set; }
    public string date_upd { get; set; }
    public string reset_password_token { get; set; }
    public string reset_password_validity { get; set; }

}

class Program
{

    static void ShowProduct(Customer customer)
    {
        Console.WriteLine($"Email: {customer.email}\tFirst Name: {customer.firstname}");
    }

    static async Task<Uri> CreateCustomerAsync(Customer customer)
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.PostAsJsonAsync("api/customers/1?output_format=JSON", customer);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }
    static void Main()
    {
        RunAsync().Wait();
    }
    static async Task RunAsync()
    {
        NetworkCredential hd = new NetworkCredential("INHFTLZLMLP1TUTJE7JL9LETCCEW63FN", "");
        HttpClientHandler handler = new HttpClientHandler {Credentials = hd };
        HttpClient client = new HttpClient(handler);

        client.BaseAddress = new Uri("http://localhost:8080/newprestashop/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            try
            {

                Customer customer = new Customer();
                var url = await CreateCustomerAsync(customer);
                // Get the product
                customer = await GetProductAsync(url.PathAndQuery);
                ShowProduct(customer);


            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

    static async Task<Customer> GetProductAsync(string path)
    {
        Customer customer = null;
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            customer = await response.Content.ReadAsAsync<Customer>();
        }
        return customer;
    }

}

} }

BaseAddress is there so that you can make all the calls relative to the the BaseAddress. BaseAddress 在那里,以便您可以进行与 BaseAddress 相关的所有调用。 It works, you just need to know some of the idiosyncrasies of BaseAddress Why is HttpClient BaseAddress not working?它有效,您只需要了解 BaseAddress 的一些特性为什么 HttpClient BaseAddress 不起作用?

But your problem is that you are instantiating a new HttpClient in each method.但是你的问题是你在每个方法中实例化一个新的 HttpClient 。

static async Task<Uri> CreateCustomerAsync(Customer customer)
{
    HttpClient client = new HttpClient();
    //you never set the BaseAddress 
    //or the authentication information
    //before making a call to a relative url!
    HttpResponseMessage response = await client.PostAsJsonAsync("api/customers/1?output_format=JSON", customer);
    response.EnsureSuccessStatusCode();

    // return URI of the created resource.
    return response.Headers.Location;
}

A better way would be to wrap the HttpClient call in a class and it up in the constructor, then share it in any of your methods更好的方法是将 HttpClient 调用包装在一个类中,并将其包装在构造函数中,然后在您的任何方法中共享它

    public WrapperClass(Uri url, string username, string password, string proxyUrl = "")
    {
        if (url == null)
            // ReSharper disable once UseNameofExpression
            throw new ArgumentNullException("url");
        if (string.IsNullOrWhiteSpace(username))
            // ReSharper disable once UseNameofExpression
            throw new ArgumentNullException("username");
        if (string.IsNullOrWhiteSpace(password))
            // ReSharper disable once UseNameofExpression
            throw new ArgumentNullException("password");
        //or set your credentials in the HttpClientHandler
        var authenticationHeaderValue = new AuthenticationHeaderValue("Basic",
            // ReSharper disable once UseStringInterpolation
            Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", username, password))));

        _httpClient = string.IsNullOrWhiteSpace(proxyUrl)
            ? new HttpClient
            {
                DefaultRequestHeaders = { Authorization = authenticationHeaderValue },
                BaseAddress = url
            }
            : new HttpClient(new HttpClientHandler
            {
                UseProxy = true,
                Proxy = new WebProxy
                {
                    Address = new Uri(proxyUrl),
                    BypassProxyOnLocal = false,
                    UseDefaultCredentials = true
                }
            })
            {
                DefaultRequestHeaders = { Authorization = authenticationHeaderValue },
                BaseAddress = url
            };

        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.AcceptEncoding.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<Member> SomeCallToHttpClient(string organizationId)
    {
        var task = await _httpClient.GetStringAsync(<your relative url>));

        return JsonConvert.DeserializeObject<SomeType>(task,
            new JsonSerializerSettings {ContractResolver = new CamelCasePropertyNamesContractResolver()});
    }

I bet you need the complete url address.我敢打赌你需要完整的 url 地址。 The url is not relative to the caller when using HttpClient.使用 HttpClient 时,该 url 与调用方无关。

static async Task<Uri> CreateCustomerAsync(Customer customer)
{
   HttpClient client = new HttpClient();
   HttpResponseMessage response = await client.PostAsJsonAsync("http://www.fullyqualifiedpath.com/api/customers/1?output_format=JSON", customer);
   response.EnsureSuccessStatusCode();

   // return URI of the created resource.
   return response.Headers.Location;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 '提供了一个无效的请求 URI。 请求 URI 必须是绝对 URI,或者必须设置 BaseAddress。 - 'An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set.' 如何解决&#39;提供了无效的请求URI。 请求URI必须是绝对URI或必须设置BaseAddress” - How to fix 'An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set' &#39;提供了无效的请求URI。 连接到AF中的SP的请求URI必须是绝对URI或必须设置BaseAddress - 'An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set' exception connecting to a SP in an AF 提供了无效的请求URI。 (堆栈跟踪中没有有用的信息) - An invalid request URI was provided. (No helpful info in the stack trace) HTTPClient 错误提供了无效的请求 URI - HTTPClient error An invalid request URI was provided 使用Webservice请求uri太久 - Request uri too long with webservice redirect_uri URL必须是绝对错误 - The redirect_uri URL must be absolute error 如何获取RESTful Web服务的请求URI - How to get the request URI of a RESTful webservice 提供的URI方案“ https”无效 - The provided URI scheme 'https' is invalid 为什么这个 HttpRequestMessage 的请求 URI 无效? - Why is this HttpRequestMessage's request URI invalid?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM