2016-10-04 16 views
1

私は鍵を返すサービスを統合していたとき、私、次の形式であるURLにGETリクエスト:のHttpClientアクセスURL「@」(アットマーク)

https://username:[email protected]/refresh.key 

私がアクセス私のブラウザでURL、それは私が、私はそれがURLに'@'とは何かを持っていると思いますが、私401

HttpClient _client = new HttpClient(); 
var response = await _client.GetAsync(@"https://username:[email protected]/refresh.key"); // Returns a 401 

を取得HttpClientを使用してGET要求を行うときで、期待通りの新しいキーを返しますそれを修正する方法がわからない、私はそれを'%40'に置き換えようとしたが、私がそれをするとき私はUriFormatExceptionを得る。

誰でもこれを行う方法を知っていますか?

+0

URIのために働く:password'資格情報は、基本認証を使用して要求に変換する必要がありますhttp://www.baeldung.com/httpclient-4-basic-authentication – Dai

答えて

1

あなたは以下のコードを試すことができ、HttpClientをのAuthorizationヘッダーを変更する必要があります。

HttpClient _client = new HttpClient(); 
byte[] usernamePasswordBytes = Encoding.ASCII.GetBytes("user:pass"); 
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(usernamePasswordBytes)); 
var response = await _client.GetAsync(@"https://service.com/refresh.key"); 

PS:このようなユーザー名:[email protected]リクエストはBasicAuthenticationリクエストですので、基本的な認証リクエストを作成しようとしています。

希望これはユーザ名 `であなた

1

URLにクレデンシャルを入力する必要はありません。代わりにあなたが行うことができます。

using (var handler = new HttpClientHandler {Credentials = new NetworkCredential("username", "password")}) { 
    using (HttpClient _client = new HttpClient(handler)) { 
      var response = await _client.GetAsync(@"https://service.com/refresh.key"); 
    } 
} 
関連する問題