2017-05-05 638 views
0

我試圖消耗.NET中使用HttpClient的Web服務後,我的確在msdn提供了無效的請求URI。請求URI必須是絕對URI或BaseAddress必須設置。試圖消耗web服務

提到的所有步驟Ø出現以下情況例外:了無效的請求URI提供了依據。請求URI必須是絕對URI或BaseAddress必須設置。

這裏是我的類

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

} 

}

+0

你確定你的Web服務已經啓動並運行在http:// localhost:8080?我將啓動web api項目,並在您嘗試訪問的控制器(newprestashop)的方法(索引)開始處添加一個斷點。然後,從您的客戶打電話。 –

+0

我測試郵政人工作很好 –

回答

2

BaseAddress在那裏,以便您可以進行所有相對於BaseAddress的調用。它的工作原理,你只需要知道基地址的一些特質Why is HttpClient BaseAddress not working?

但是你的問題是你正在實例化一個新的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; 
} 

一個更好的方法是將包裹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()}); 
    } 
+0

非常感謝你 –

2

我敢打賭,你需要完整的URL地址。使用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; 
    } 
+0

偉大的異常已經消失,但它給了另一個「響應狀態代碼不表示成功:401(未經授權)。」 –

+0

這意味着您需要在進行api調用之前進行身份驗證。由於缺乏授權,終點達到並被拒絕。 –

+0

您的授權問題與您的BaseAddress問題相同。你實例化HttpClient並且從不設置值。看到我的答案。 – Fran