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

时间:2017-08-11 09:48:59

标签: c# dotnet-httpclient

我尝试使用带有HttpClient的C#执行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#中写这样的话:

    public async Task<HttpResponseMessage> DoTheTest()
    {
        using (var handler = new HttpClientHandler { Credentials = new System.Net.NetworkCredential("userName", "pwd") })
        {
            HttpClient cons = new HttpClient(handler);
            cons.BaseAddress = new Uri("http://serverName.com/");
            cons.DefaultRequestHeaders.Accept.Clear();
            cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            using (cons)
            {
//always hangs here.
                var response = await cons.GetAsync("ur?fields=cams_id;email");
                if (response.IsSuccessStatusCode)
                {
                    return response;
                }
            }
        }
        return null;
    }

但是,它不起作用。你能帮我解决&#34;翻译&#34;?

顺便说一句,这段代码在powershell中适用于我。到目前为止,在C#中没有任何作用:

$user = 'userName'
$pass = 'pwd'

$pair = "$($user):$($pass)"

$encodedCreds =   [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$Headers = @{
    Authorization = $basicAuthValue
}


Invoke-RestMethod -Uri 'http://serverName.com/ur?fields=cams_id;email'-Headers $headers

并且这个在Visual Studio C#中再次起作用:

        WebRequest httpWebRequest = HttpWebRequest.Create("http://serverName.com/ur?fields=cams_id;email");
        ((HttpWebRequest)httpWebRequest).ProtocolVersion = HttpVersion.Version10;
        String username = "userName";
        String password = "pwd";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
        httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
        //hangs here, too
        using (var response = httpWebRequest.GetResponse())
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var result = reader.ReadToEnd();
            Assert.IsTrue(!String.IsNullOrEmpty(result));
        }

1 个答案:

答案 0 :(得分:1)

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