2017-05-05 10 views
0

을 소비하려고하고 난 msdn유효하지 않은 요청 URI가 제공되었습니다. 요청 URI는 절대 URI이거나 BaseAddress가 설정되어야합니다. 내가 .NET에서 HttpClient를을 사용하여 웹 서비스를 소비하려고 오전 웹 서비스

에 언급 된 모든 단계를 한 후 O 다음과 같은 예외 가져 오기 : 가 잘못된 요청 URI이 제공되었다. 요청 URI는 절대 URI이거나 BaseAddress가 설정되어야합니다.

여기 당신이 전체 URL 주소가 필요 내기 내 수업

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

이 확실 웹 서비스가있다 있습니까 당신의 방법 중 하나에 그것을 공유하고 http : // localhost : 8080에서 실행 중입니까? 나는 웹 API 프로젝트를 시작하고 당신이 치려고하는 컨트롤러 (newprestashop)의 메소드 (인덱스)의 시작 부분에 중단 점을 추가한다. 그런 다음 고객에게 전화하십시오. –

+0

나는 위 사람이 잘 작동하는지 테스트한다. –

답변

2

BaseAddress가 있으므로 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를 사용할 때 호출자와 관련이 없습니다.

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