C# 简单Http请求在Visual Studio中执行时挂起,在powershell中工作

C# 简单Http请求在Visual Studio中执行时挂起,在powershell中工作,c#,dotnet-httpclient,C#,Dotnet Httpclient,我正试图用C#withHttpClient执行一个http请求。但是,每次调用GetAsync时,代码都会挂起。powershell中也有类似的故事 这是我的java工作示例: Authenticator.setDefault( new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordA

我正试图用C#with
HttpClient
执行一个http请求。但是,每次调用GetAsync时,代码都会挂起。powershell中也有类似的故事

这是我的java工作示例:

Authenticator.setDefault( new Authenticator()
{
    @Override
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication( "userName", "pwd".toCharArray());
    }
});
URL url = new URL( "http://serverName.com/ur?fields=cams_id;email");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod( "GET");
conn.setRequestProperty( "Accept", "application/json");

if( conn.getResponseCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + conn.getResponseCode()); }

BufferedReader br = new BufferedReader( new InputStreamReader( (conn.getInputStream())));

String output;
System.out.println( "Output from Server .... \n");
while( (output = br.readLine()) != null)
{
    System.out.println( output);
}

conn.disconnect();
我试着这样用C写:

这个在Visual Studio C中同样不起作用:


您对
.Result
的调用可能导致死锁。您应该重构该方法以使用async/await

public async Task BasicTest()
然后,您需要将
GetAsync
调用更新为:

HttpResponseMessage response = await cons.GetAsync("ur?fields=cams_id;email");
编辑:看起来请求超时了。我相信默认的超时时间是100秒

尝试更改超时以查看是否是超时导致挂起:

cons.Timeout = TimeSpan.FromSeconds(5);

问题不在于代码,而在于机器。杀死Sophos SSL VPN客户端后,代码运行没有问题。仍然不确定为什么powershell工作而c#(在VS或外部)不工作。

您应该避免调用异步方法的
。Result
。改用
async/await
。这会造成问题吗?结果不到一秒就出来了,我只是想让它工作起来。我怀疑它默认为http1.1。您需要将客户端设置为http1.0,如下所示:HttpWebRequest=(HttpWebRequest)WebRequest.Create(“URL”);request.ProtocolVersion=HttpVersion.Version10;downvote的原因之一可能是您使用了一个描述为“请勿使用”<代码>的标记-使用[apache commons httpclient]、[apache-httpclient-4.x]或[dotnet httpclient]这里不是downvoter,但它不起作用。没有任何意义。有例外吗?还是就这么挂着?或者别的什么?
public async Task BasicTest()
HttpResponseMessage response = await cons.GetAsync("ur?fields=cams_id;email");
cons.Timeout = TimeSpan.FromSeconds(5);