我使用WebClient从网站下载一个字符串(只包含纯文本,没有别的),所以我使用DownloadString方法:
WebClient wc = new WebClient();
string str = wc.DownloadString("http://blah");
Run Code Online (Sandbox Code Playgroud)
它运行正常,但问题是它第一次下载字符串需要很长时间,比如5秒.之后它运作得很快.为什么会发生这种情况,如何解决这个问题呢?
我想从FTP服务器读取文件而不将其下载到本地文件.我写了一个函数,但它不起作用:
private string GetServerVersion()
{
WebClient request = new WebClient();
string url = FtpPath + FileName;
string version = "";
request.Credentials = new NetworkCredential(ftp_user, ftp_pas);
try
{
byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName);
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
}
catch (WebException e)
{
}
return version;
}
Run Code Online (Sandbox Code Playgroud) 我目前有这个用于我的WebClient URL
WebClient Detail = new WebClient();
Detail.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
Detail.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" + ListingID.Text + ".xml"));
Run Code Online (Sandbox Code Playgroud)
我想要做的是使用这个字符串:
void ListBoxSelectionChanged(object sender, SelectionChangedEventArgs args)
{
var lbi = ((sender as ListBox).SelectedItem as TradeItem);
if(lbi != null)
{
string id = lbi.ListingId.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
作为WbeClient URL的一部分.
例:
WebClient Detail = new WebClient();
Detail.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Detail_DownloadStringCompleted);
Detail.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Listings/" + id + ".xml"));
Run Code Online (Sandbox Code Playgroud)
无论如何在URL中使用此字符串如上所示?
完整代码#####################################
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media; …Run Code Online (Sandbox Code Playgroud) 我使用以下代码从互联网获取html数据:
WebProxy p = new WebProxy("localproxyIP:8080", true);
p.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = p;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.google.com");
Run Code Online (Sandbox Code Playgroud)
但出现以下错误:"需要代理身份验证".我无法使用默认代理,因为我的代码是在没有默认代理设置的特殊帐户下从Windows服务运行的.所以,我想在我的代码中指定所有代理设置.请告诉我如何解决此错误.
我正在使用此代码将参数发送到网页并从中获取正确的响应.
System.Net.WebClient oWeb = new System.Net.WebClient();
oWeb.Proxy = System.Net.WebRequest.DefaultWebProxy;
oWeb.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
oWeb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] bytArguments = System.Text.Encoding.ASCII.GetBytes("value1=123&value2=xyz");
byte[] bytRetData = oWeb.UploadData("http://website.com/file.php", "POST", bytArguments);
response = System.Text.Encoding.ASCII.GetString(bytRetData);
Run Code Online (Sandbox Code Playgroud)
但现在我想发送一个像(.doc)的文件+上面的参数(value1,value2),但我不知道该怎么做.
考虑一个简单的C#.NET Framework 4.0应用程序,它:
这是一个工作正常的样本:
using System;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string URL_status = "http://localhost/status";
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(URL_status), "NTLM", new NetworkCredential("username", "password", "domain"));
WebClient WebClient = new WebClient();
WebClient.Credentials = myCache;
for (int i = 1; i <= 5; i++)
{
string Result = WebClient.DownloadString(new Uri(URL_status));
Console.WriteLine("Try " + i.ToString() + ": " + Result);
}
Console.Write("Done");
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题:
启用跟踪时,我发现NTLM身份验证不会持久存在. …
当网络连接丢失3分钟或更长时间时,下面的WPF代码将永久挂起.当连接恢复时,它既不会抛出也不会继续下载或超时.如果网络连接在较短的时间内丢失(例如半分钟),则在连接恢复后会丢失.如何让网络中断更加强大?
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows;
namespace WebClientAsync
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged +=
(sender, e) => Dispatcher.Invoke(delegate()
{
this.Title = "Network is " + (e.IsAvailable ? " available" : "down");
});
}
const string SRC = "http://ovh.net/files/10Mio.dat";
const string TARGET = @"d:\stuff\10Mio.dat";
private async void btnDownload_Click(object sender, RoutedEventArgs e)
{
btnDownload.IsEnabled = false;
btnDownload.Content = "Downloading " + SRC;
try {
using (var wcl = new WebClient())
{ …Run Code Online (Sandbox Code Playgroud) 我没有看到这两种方法之间有任何主要的时间复杂度差异,它们都有工作魅力,我想了解这两种方法之间的主要区别是什么
我正在从服务中收集学生对象。
bodyToMono 参数化类型参考
public Mono<Collection<Student>> getStudents(String id) {
return webClient
.get()
.uri(uriBuilder -> uriBuilder
.path("/students/{0}")
.build(id))
.retrieve()
.onStatus(HttpStatus::isError, resp -> resp.createException()
.map(WebClientGraphqlException::new)
.flatMap(Mono::error)
).bodyToMono(new ParameterizedTypeReference<Collection<Student>>() {}); // This Line
}
Run Code Online (Sandbox Code Playgroud)
bodyToFlux 收集器
public Mono<Collection<Student>> getStudents(String id) {
return webClient
.get()
.uri(uriBuilder -> uriBuilder
.path("/students/{0}")
.build(id))
.retrieve()
.onStatus(HttpStatus::isError, resp -> resp.createException()
.map(WebClientGraphqlException::new)
.flatMap(Mono::error)
).bodyToFlux(Student.class).collect(Collectors.toList()); // This Line
}
Run Code Online (Sandbox Code Playgroud) 我试图从我们的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) 我试图在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) webclient ×10
c# ×8
.net ×4
ntlm ×2
wpf ×2
asynchronous ×1
download ×1
file-upload ×1
ftp ×1
iis ×1
java ×1
performance ×1
silverlight ×1
spring-boot ×1
system.net ×1
webproxy ×1