我有以下方法返回Http status code给定的Url:
public static async void makeRequest(int row, string url)
{
string result;
Stopwatch sw = new Stopwatch(); sw.Start();
try
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = new HttpResponseMessage();
response = await client.GetAsync(url);
// dump contents of header
Console.WriteLine(response.Headers.ToString());
if (response.IsSuccessStatusCode)
{
result = ((int)response.StatusCode).ToString();
}
else
{
result = ((int)response.StatusCode).ToString();
}
}
}
catch (HttpRequestException hre)
{
result = "Server unreachable";
}
sw.Stop();
long time = sw.ElapsedTicks / (Stopwatch.Frequency / …Run Code Online (Sandbox Code Playgroud) 该应用程序使用client.PostAsync()发送帖子.我希望它不要遵循302重定向.
怎么样?
我想我可以AllowAutoRedirect按照这个答案中的描述进行设置.
但是如何HttpWebRequest在PostAsync()调用中使用?
我想用 C# 做一个简单的 HTTP 请求,但有些东西不起作用,我得到的只是403 Forbidden状态代码。
当我尝试在 Postman 中执行相同的请求时,一切正常。我尝试运行 Fiddler 并查看 Postman 发送的所有标头。我复制粘贴了所有这些,但我仍然收到403 Forbidden了 C# 代码发送的请求。
public static void Main(string[] args)
{
FlurlHttp.Configure(settings => {
settings.HttpClientFactory = new MyClientFactory();
});
var url = "https://example.com"
.AppendPathSegments(new[] { "v1", "oauth", "accesstoken" })
.SetQueryParam("grant_type", "client_credentials")
.AllowAnyHttpStatus()
.WithBasicAuth("username", "password")
.WithHeaders(new {
User_Agent = "Something/0.4.0 Dalvik/2.1.0 (Linux; U; Android 5.1.1; SM-G975F Build/NRD90M)",
X_Secret_Header = "secret_encoded_value",
accept_encoding = "gzip, deflate",
Accept = "*/*"
});
HttpResponseMessage msg = url.GetAsync().Result; …Run Code Online (Sandbox Code Playgroud)