标签: webclient

System.Net.WebClient奇怪地失败了

我试图从我们的TFS服务器上的报告服务实例下载一些数据.
鉴于代码应该在未加入域的计算机上运行,​​我想我会自己设置凭据.没有运气,得到了一个HTTP 401 Unauthorized返回.好的,所以我联系了Fiddler看看发生了什么.

但是当我得到Heisenberged时 - 这个电话现在顺利完成了.因此认证通过Fiddler连接,但没有它就失败了.Webclient是破碎的还是我错过了一些深刻的东西?

private void ThisWorksWhenDomainJoined()
    {
        WebClient wc = new WebClient();
        wc.Credentials = CredentialCache.DefaultNetworkCredentials;
        wc.DownloadString("http://teamfoundationserver/reports/........");  //Works
    }

    private void ThisDoesntWork()
    {
        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential("username", "password", "domain");
        wc.DownloadString("http://teamfoundationserver/reports/........");  //blows up wih HTTP 401
    }
Run Code Online (Sandbox Code Playgroud)

c# system.net webclient

12
推荐指数
1
解决办法
1万
查看次数

System.Net.WebClient不适用于Windows身份验证

我试图在WinForms应用程序中使用System.Net.WebClient将文件上传到具有Windows身份验证的IIS6服务器,因为它只是"身份验证"方法.

WebClient myWebClient = new WebClient();
myWebClient.Credentials = new System.Net.NetworkCredential(@"boxname\peter", "mypassword"); 
byte[] responseArray = myWebClient.UploadFile("http://localhost/upload.aspx", fileName);
Run Code Online (Sandbox Code Playgroud)

我得到一个'远程服务器返回错误:(401)未授权',实际上它是401.2

客户端和IIS都在同一台Windows Server 2003 Dev计算机上.

当我尝试在Firefox中打开页面并输入与代码中相同的正确凭据时,页面出现.但是,当使用IE8时,我得到相同的401.2错误.

试过Chrome和Opera,他们都工作.

我在IE Internet选项中启用了"启用集成Windows身份验证".

安全事件日志具有失败审核:

Logon Failure:
    Reason:     An error occurred during logon
    User Name:  peter
    Domain:     boxname
    Logon Type: 3
    Logon Process:  ÈùÄ
    Authentication Package: NTLM
    Workstation Name:   boxname
    Status code:    0xC000006D
    Substatus code: 0x0
    Caller User Name:   -
    Caller Domain:  -
    Caller Logon ID:    -
    Caller Process ID:  -
    Transited Services: -
    Source Network Address: 127.0.0.1
    Source …
Run Code Online (Sandbox Code Playgroud)

iis ntlm webclient

12
推荐指数
1
解决办法
2万
查看次数

System.Net.WebClient与代理身份验证407错误

我正在尝试弄清楚如何在使用System.Net.WebClient类时强大地处理代理身份验证错误(HTTP 407状态代码).

在该领域,我们看到许多用户接收到407代理身份验证WebException,但我不确定什么是一个好的默认策略.在.Net 2.0/3.5中,代理身份验证设置应该从Internet Explorer系统设置继承.Firefox,Opera和Chrome使用这些相同的设置.

这是我们使用的基本代码:

using System.Net;

string url = "http://www.mysite.com";
WebClient webClient = new WebClient();
byte[] data = webClient.DownloadFile(url);
Run Code Online (Sandbox Code Playgroud)

当此代码失败时,我们打开用户的浏览器并将其发送到帮助页面.从我们的网络日志中,我们知道这些客户可以在其浏览器中成功连接.也许他们在进入我们的帮助页面之前手动输入他们的代理用户名和密码?我们不知道.

似乎我们可以使用WebClient.UseDefaultCredentials,但是如果WebClient正在使用系统设置,这似乎是多余的.

任何帮助表示赞赏.

.net proxy webclient

12
推荐指数
3
解决办法
1万
查看次数

WebClient - 远程服务器返回错误:(403)禁止

从浏览器打开公共页面工作正常.

使用WebClient下载同一页面抛出 - (403)禁止.

这里发生了什么 ?

以下是Web上特定页面的快速复制/粘贴示例(在控制台应用程序上使用):

try
{
    WebClient webClient = new WebClient();
    string content = webClient.DownloadString("http://he.wikisource.org/wiki/%D7%A9%D7%95%D7%9C%D7%97%D7%9F_%D7%A2%D7%A8%D7%95%D7%9A_%D7%90%D7%95%D7%A8%D7%97_%D7%97%D7%99%D7%99%D7%9D_%D7%90_%D7%90");
}
catch (Exception ex)
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

c# webclient

12
推荐指数
1
解决办法
3万
查看次数

使用WebClient和C#,即使响应是(400)错误请求,如何获取返回的数据?

我正在使用谷歌翻译API,并试图捕获我收到错误时返回的数据.(仅供参考:我知道API密钥错了,我只是在测试它).

问题是,通过单击链接可以看到浏览器显示错误信息,但C#抛出WebException,我似乎无法获取响应数据.

这是我的代码:

string url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world";
WebClient clnt = new WebClient();

//Get string response
try
{
    strResponse = clnt.DownloadString(url);
    System.Diagnostics.Debug.Print(strResponse);
}
catch (Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

即使响应是(400)错误请求(或任何其他错误共振),如何返回JSON错误?我需要使用除了以外的其他类WebClient吗?

c# webclient http-status-code-400

12
推荐指数
1
解决办法
1万
查看次数

使用webclient类将文件上载到文件服务器

目前我有一个应用程序从我的Web应用程序接收上传的文件.我现在需要将该文件传输到恰好位于同一网络上的文件服务器(但事实并非总是如此).

我试图在C#.NET中使用webclient类.

    string filePath = "C:\\test\\564.flv";
    try
    {
        WebClient client = new WebClient();

        NetworkCredential nc = new NetworkCredential(uName, password);

        Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv");
        client.Credentials = nc;
        byte[] arrReturn = client.UploadFile(addy, filePath);
        Console.WriteLine(arrReturn.ToString());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
Run Code Online (Sandbox Code Playgroud)

位于192.168.1.28的计算机是文件服务器,共享c:\ Files.截至目前,我收到登录失败的错误用户名或密码错误,但我可以打开资源管理器并输入该路径成功登录.我也可以使用远程桌面登录,所以我知道用户帐户有效.

有关此错误的任何想法?是否可以像这样直接传输文件?使用webclient类或者其他类?

c# webclient file-upload fileserver

11
推荐指数
1
解决办法
10万
查看次数

是否应该在WebException中处理WebResponse引用,如果从WebClient引发?

相关问题:.Net中的WebClient没有释放套接字资源

在调试资源泄漏问题时,我注意到System.Net.WebException(非一次性类型)包含对System.Net.WebResponse(一次性类型)的引用.我想知道在显式处理WebResponse以下代码段中的as 时是否应该处理此引用.

using (WebClient client = new WebClient())
{
    WebException ex = Assert.Throws<WebException>(() => client.OpenRead(myUri));
    Assert.That(
        ((HttpWebResponse)ex.Response).StatusCode,
        Is.EqualTo(HttpStatusCode.ServiceUnavailable));
}
Run Code Online (Sandbox Code Playgroud)

WebException.WebResponse引用是现有引用的副本WebClient.我认为它会被处理掉,WebClient.Dispose但事实并非如此,因为WebClient它不会覆盖受保护的Component.Dispose(bool)基本方法.实际上,反汇编表明WebResponse资源从未被处理掉,而是在不再需要时设置为null.

public Stream OpenRead(Uri address)
{
    Stream stream2;

    // --- removed for brevity ---

    WebRequest request = null;
    this.ClearWebClientState();
    try
    {
        request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address));
        Stream responseStream = (this.m_WebResponse = this.GetWebResponse(request)).GetResponseStream();

        // --- removed for brevity ---

        stream2 = responseStream; …
Run Code Online (Sandbox Code Playgroud)

.net dispose webclient httpwebrequest httpwebresponse

11
推荐指数
1
解决办法
1359
查看次数

如何将WebClient.DownloadFile与摘要式身份验证和查询字符串一起使用

如何使用WebClient.DownloadFile摘要式身份验证和查询字符串?

当我尝试使用它时,我得到401响应.

这是Apache错误日志:

[Tue Jun 24 17:31:49 2014] [error] [client x.x.x.x] Digest: uri mismatch - </file-1.php> does not match request-uri </file-1.php?since=1403587422>
Run Code Online (Sandbox Code Playgroud)

以下是我尝试下载文件的方法:

Uri uri = new Uri("http://example.com/file-1.php?since=1403587422");
WebClient webClient = new WebClient();
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(
  new Uri(uri.GetLeftPart(UriPartial.Authority)),
  "Digest",
  new NetworkCredential("username", "password")
);
webClient.Credentials = credentialCache;
webClient.DownloadFile(uri, file.OutputFile);
Run Code Online (Sandbox Code Playgroud)

.net c# apache webclient digest-authentication

11
推荐指数
1
解决办法
1547
查看次数

当有请求正文时模拟 WebClient 帖子

有几个关于模拟 WebClient 对象的问题提供了有用的答案。但我在用身体发帖时仍然遇到问题。我只是使用Mockito而不是mockwebserver

这是我正在测试的方法:

public class RestClient extends BaseRestClient {
 ...
 public <T,G> Mono<T> post(String url, G req, Class<T> resp) throws IOException {
        Mono<T> response = null;

        response = this.getWebClient().post()
                    .uri(url)
                    .header(HttpHeaders.CONTENT_TYPE,JSON_CONTENT_TYPE)
                    .accept(MediaType.APPLICATION_JSON)
                    //.body(BodyInserters.fromObject(req))
                    .header(HttpHeaders.AUTHORIZATION, BEARER + token)
                    .retrieve()
                    .bodyToMono(resp).log();

        return response.map(resp::cast);
    }
 ...
Run Code Online (Sandbox Code Playgroud)

请注意注释掉的正文线。

这是与上面的代码配合良好的测试 - 再次注意测试中注释掉的行:

@Mock
WebClient webClient;

@Mock
WebClient.RequestBodyUriSpec requestBodyUriSpec;

@Mock
WebClient.RequestHeadersSpec requestHeadersSpec;

@Mock
WebClient.RequestBodySpec requestBodySpec;

@Mock
WebClient.ResponseSpec responseSpec;

@InjectMocks
RestClient restClient;

@Test
    public void postTest() throws IOException {
        when(webClient.post()).thenReturn(requestBodyUriSpec);
        when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec);
        when(requestBodySpec.header(any(),any())).thenReturn(requestBodySpec); …
Run Code Online (Sandbox Code Playgroud)

java spring unit-testing webclient mockito

11
推荐指数
1
解决办法
4万
查看次数

`servletRequest 不能为 null` -&gt; SpringBoot - WebClient - 使用 Keycloak 的 GET 请求

我正在尝试在两个微服务之间发出 GET 请求(使用 Keycloak 身份验证)。

\n

假设微服务 A 正在向微服务 B 请求一些资源。\n微服务 B 有一个 GET 端点,它似乎可以工作,因为在从邮递员或 intelliJ http_client 发出请求时我可以看到正确的响应。

\n

在微服务 AI 中尝试发出请求(我确实尝试发出阻塞和非阻塞请求):

\n
    \n
  • 阻止请求
  • \n
\n
String response = webClient.mutate()\n                .baseUrl(this.serverUri)\n                .build().get()\n                .uri(uriBuilder -> uriBuilder\n                        .path("/users/tokens/{id}")\n                        .build(userId))\n                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)\n                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction\n                        .clientRegistrationId("keycloak"))\n                .retrieve()\n                .bodyToMono(String.class)\n                .doOnError(RuntimeException::new)\n                .block();\n
Run Code Online (Sandbox Code Playgroud)\n
    \n
  • 非阻塞请求:
  • \n
\n
        webClient.mutate()\n                .baseUrl(this.serverUri)\n                .build().get()\n                .uri(uriBuilder -> uriBuilder\n                        .path("/users/tokens/{id}")\n                        .build(userId))\n                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)\n                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction\n                        .clientRegistrationId("keycloak"))\n                .retrieve()\n                .bodyToMono(String.class)\n                .subscribe(resp -> {\n                    JSONObject jsonObject = new JSONObject(resp);\n                    JSONArray jsonArray = jsonObject.getJSONArray("Tokens");\n                    for (int i …
Run Code Online (Sandbox Code Playgroud)

webclient httprequest blocking spring-boot

11
推荐指数
1
解决办法
5662
查看次数