我正在尝试使用HttpClient需要基本HTTP身份验证的第三方服务.我正在使用AuthenticationHeaderValue.这是我到目前为止所提出的:
HttpRequestMessage<RequestType> request =
new HttpRequestMessage<RequestType>(
new RequestType("third-party-vendor-action"),
MediaTypeHeaderValue.Parse("application/xml"));
request.Headers.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "username", "password"))));
var task = client.PostAsync(Uri, request.Content);
ResponseType response = task.ContinueWith(
t =>
{
return t.Result.Content.ReadAsAsync<ResponseType>();
}).Unwrap().Result;
Run Code Online (Sandbox Code Playgroud)
看起来POST动作工作正常,但我没有收到我期望的数据.通过一些试验和错误,并最终使用Fiddler来嗅探原始流量,我发现授权标头没有被发送.
我已经看过了,但我认为我已经将指定的身份验证方案指定为AuthenticationHeaderValue构造函数的一部分.
有没有我错过的东西?
该应用程序使用client.PostAsync()发送帖子.我希望它不要遵循302重定向.
怎么样?
我想我可以AllowAutoRedirect按照这个答案中的描述进行设置.
但是如何HttpWebRequest在PostAsync()调用中使用?
我已经制作了一个基本的扩展方法来为我添加重试功能HttpClient.PostAsync:
public static async Task<HttpResponseMessage> PostWithRetryAsync(this HttpClient httpClient, Uri uri, HttpContent content, int maxAttempts, Action<int> logRetry)
{
if (maxAttempts < 1)
throw new ArgumentOutOfRangeException(nameof(maxAttempts), "Max number of attempts cannot be less than 1.");
var attempt = 1;
while (attempt <= maxAttempts)
{
if (attempt > 1)
logRetry(attempt);
try
{
var response = await httpClient.PostAsync(uri, content).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return response;
}
catch (HttpRequestException)
{
++attempt;
if (attempt > maxAttempts)
throw;
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了以下错误:
错误CS0161'HttpClientExtensions.PostWithRetryAsync(HttpClient,Uri,HttpContent,int,Action)':并非所有代码路径都返回一个值.
如果我throw new InvalidOperationException()在最后添加(或者 …
使用HttpClient类访问Delicious API时,我遇到了一些问题.我有以下代码:
try
{
const string uriSources = "https://api.del.icio.us/v1/tags/bundles/all?private={myKey}";
using (var handler = new HttpClientHandler { Credentials = new
NetworkCredential("MyUSER", "MyPASS") })
{
using (var client = new HttpClient(handler))
{
var result = await client.GetStringAsync(uriSources);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR...", MessageBoxButton.OK);
}
Run Code Online (Sandbox Code Playgroud)
运行上面的代码时,我得到以下内容:响应状态代码不表示成功:401(未授权).
那么,我怎么能得到这个工作?可能吗?
提前致谢
问候!
c# windows-phone-7 dotnet-httpclient windows-phone-8 asynchttpclient
我有以下代码:
...
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("OAuth2", Contract.AccessToken);
string result = await PostRequest.AuthenticatedGetData(fullUrl, null, authHeaders);
return result;
...
public static async Task<string> AuthenticatedGetData(string url, FormUrlEncodedContent data, AuthenticationHeaderValue authValue)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue.Parameter);
HttpResponseMessage response = await client.PostAsync(new Uri(url), data);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
Run Code Online (Sandbox Code Playgroud)
响应=等待部分只是继续循环,没有任何反应.我有什么想法我做错了吗?
问题是,我如何发送以下标题:
Authorization: OAuth2 ACCESS_TOKEN
Run Code Online (Sandbox Code Playgroud)
到外部网络api
我应该等待 ReadAsStringAsync(),如果我期待已久的上我在进行了响应ReadAsStringAsync()?为了进一步澄清,下列之间有什么不同或正确的方法?它们实际上是一样的吗?
var response = await httpClient.GetAsync("something");
var content = await response.Content.ReadAsStringAsync();
return new AvailableViewingTimesMapper().Map(content);
Run Code Online (Sandbox Code Playgroud)
要么
var response = await httpClient.GetAsync("something");
var content = response.Content.ReadAsStringAsync();
return new AvailableViewingTimesMapper().Map(content.Result);
Run Code Online (Sandbox Code Playgroud) 前一段时间我使用HttpClient该类实现了一些使用REST Api的代码.
using (var client = new HttpClient() { BaseAddress = new Uri(@"https://thirdparty.com") })
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(...);
var uri = new Uri(@"rest/api/foo", UriKind.Relative);
var content = new StringContent(json.ToString());
using (var response = await client.PostAsync(uri, content))
{
// etc ...
}
}
Run Code Online (Sandbox Code Playgroud)
对于测试和生产环境(每个环境都访问测试/生产环境),此代码似乎完全正常.最近,我们开始只在生产环境中获得HttpRequestException :System.Net.Http.HttpRequestException: Error while copying content to a stream.
这看起来有点奇怪,所以我使用Postman发送相同的消息,它工作得很好.我不确定为什么我们的代码失败了,Postman正在工作.我更改了json数据中的参数(状态从"NY"到"NV"),我们的.NET代码运行正常 - 当然我们不能只发送错误的json数据,所以这不是一个解决方案; 这更像是一个观察结果,完全相同的代码在不同内容下运行良好.
有趣的是,我们可以通过两个代码更改来解决这个问题.首先,Postman能够使用该RestSharp包生成有效的C#代码.或者,我从另一个指向使用HttpVersion 1.0的问题中找到答案:
using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
{
request.Version = HttpVersion.Version10; …Run Code Online (Sandbox Code Playgroud) 我正在进行WebCrawler 实现,但在ASP.NET Web API的HttpClient中遇到了奇怪的内存泄漏.
所以减少版本在这里:
我发现了问题,并没有HttpClient泄漏.看我的回答.
我添加了dispose没有效果:
static void Main(string[] args)
{
int waiting = 0;
const int MaxWaiting = 100;
var httpClient = new HttpClient();
foreach (var link in File.ReadAllLines("links.txt"))
{
while (waiting>=MaxWaiting)
{
Thread.Sleep(1000);
Console.WriteLine("Waiting ...");
}
httpClient.GetAsync(link)
.ContinueWith(t =>
{
try
{
var httpResponseMessage = t.Result;
if (httpResponseMessage.IsSuccessStatusCode)
httpResponseMessage.Content.LoadIntoBufferAsync()
.ContinueWith(t2=>
{
if(t2.IsFaulted)
{
httpResponseMessage.Dispose();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(t2.Exception);
}
else
{
httpResponseMessage.Content.
ReadAsStringAsync()
.ContinueWith(t3 =>
{
Interlocked.Decrement(ref waiting);
try
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(httpResponseMessage.RequestMessage.RequestUri); …Run Code Online (Sandbox Code Playgroud) 我正在使用Windows运行时组件进行API调用.直到今天早些时候,我使用了HttpClient相关的模型,System.Net但转而Windows.Web使用WinRT流.
除了将using报表,交换HttpContent到IHttpContent并使用WindowsRuntimeExtensions改变我IInputStream来Stream为JSON.NET,我没有做什么特别的事情.然而,在我的16次测试中突然有3次失败,而之前一切都运转了
所有3个(集成)测试都验证我在使用无效凭据登录时收到错误响应.还有其他测试包括登录(但使用有效的凭据),它们工作得很好.给定的错误消息属于类型AggregateException并具有消息
System.AggregateException:发生一个或多个错误.--->System.Exception:找不到元素.无法显示对话框,因为尚未设置父窗口句柄.
该异常包含HRESULT值.outerexception具有-2146233088与对应0x80131500的innerexception -2147023728对应的值0x80070490.这些都不是MSDN页面上的已知错误代码.
经过调查:
堆栈跟踪:
Result StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at xx.Models.Requests.GetRequest.<ExecuteRequestAsync>d__0.MoveNext() in c:\Users\jeroen\Github\Windows-app\xx\xx\Models\Requests\Request.cs:line 17
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) …Run Code Online (Sandbox Code Playgroud) 我有一个.NET 4.6.2控制台应用程序(使用Simple Injector).我需要调用HTTP服务.直接使用HttpClient遇到问题,我正在尝试使用HttpClientFactory(https://github.com/aspnet/HttpClientFactory).
项目/库是.NET Standard 2.0所以它应该?? 在.NET 4.6.2中工作,但它使用像IServiceCollection这样的东西,它只在Core中.
所以我的问题是我可以在非核心应用程序中使用HttpClientFactory.
c# ×9
async-await ×3
.net ×2
.net-4.5 ×1
.net-core ×1
json ×1
memory-leaks ×1
postman ×1
rest ×1
wcf-web-api ×1