Tag: httpclient

如何使用C#HttpClient PostAsync显示上传进度

我正在使用Xamarin PCL为Android和iOS创建文件上传应用程序,我已设法实现文件上传和某种进度条,但它无法正常工作。 我在堆栈溢出时看到了一些显示下载进度的答案,但我想通知我的用户有关上传进度的信息并且没有找到任何解决方案。 这是我的代码: public static async Task PostFileAsync (Stream filestream, string filename, int filesize) { var progress = new System.Net.Http.Handlers.ProgressMessageHandler (); //Progress tracking progress.HttpSendProgress += (object sender, System.Net.Http.Handlers.HttpProgressEventArgs e) => { int progressPercentage = (int)(e.BytesTransferred*100/filesize); //Raise an event that is used to update the UI UploadProgressMade(sender, new System.Net.Http.Handlers.HttpProgressEventArgs(progressPercentage, null, e.BytesTransferred, null)); }; using (var […]

使用PostAsync,HttpClient和Json从C#Metro UI客户端调用MVC4 WebAPI方法

我已经使用MVC4中的新WebAPIfunction创建了一个方法,并让它在Azure上运行。 该方法要求您发布一个包含Username和Password属性的简单LoginModel对象。 是的,我计划在经过这个减速带后再进一步确保这个:-)然后该方法以Json格式响应一个对象: 我可以使用Fiddler成功调用此方法,前提是我在请求标头中包含“Content-Type:application / json”。 它返回200,我可以进入Fiddler检查器并查看Json响应对象就好了: 然而,我在使用C#/ XAML从Windows8中的MetroUI应用程序调用此相同方法时遇到问题。 我开始在C#中使用HttpClient和新的Async概念,无论我如何格式化我的Post调用(即使明确地调用我希望Content-Type为“application / json”)Fiddler返回500错误并声明该尝试使用的是Content-Type:“text / html”。 我相信这是问题的根源: 我已经尝试了所有可以想到的东西,以便发布到这个方法并获取Json对象,这是我最近的尝试: HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); HttpContent content = new StringContent(@”{ “”Username””: “”” + Username.Text + @”, “”Password””: “”” + Password.Text + @”””}”); client.PostAsync(“http://myapi.com/authentication”, content).ContinueWith(result => { var response = result.Result; response.EnsureSuccessStatusCode(); }); 这导致500错误,Content-Type设置为“text / html” 这是另一次失败的尝试: HttpClient […]

使用WebClient或HttpClient下载文件?

我试图从URL下载文件,我必须在WebClient和HttpClient之间进行选择。 我在互联网上引用了这篇文章和其他几篇文章。 无处不在,由于其强大的异步支持和其他.Net 4.5权限,建议使用HttpClient。 但我仍然不完全相信并需要更多的投入。 我使用下面的代码从互联网上下载文件: Web客户端: WebClient client = new WebClient(); client.DownloadFile(downloadUrl, filePath); HttpClient的: using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(url)) using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync()) { } } 从我的角度来看,我只能看到使用WebClient的一个缺点,那就是非异步调用,阻塞调用线程。 但是,如果我不担心阻塞线程或使用client.DownloadFileAsync()来利用异步支持,该怎么办? 另一方面,如果我使用HttpClient,是不是我将文件的每个字节加载到内存中然后将其写入本地文件? 如果文件太大,内存开销不会很贵吗? 如果我们使用WebClient可以避免这种情况,因为它将直接写入本地文件而不会消耗系统内存。 那么,如果性能是我的首要任务,我应该使用哪种方法进行下载? 如果我的上述假设是错误的,我想澄清一下,我也愿意接受替代方法。

如何在Windows.Web.Http.HttpClient上停止凭据缓存?

我遇到一个问题,即应用程序尝试使用不同的身份validation方法从同一服务器访问资源,这两种方法是: 证书(NTLM,基础等) OAuth(持票人) 设置HttpBaseProtocolFilter HttpBaseProtocolFilter设置为: 禁用缓存 禁用自动UI凭据请求弹出窗口 码 HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter(); filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent; filter.AllowUI = false; 添加服务器凭据 如果资源需要凭证,那么我使用: filter.ServerCredential = new PasswordCredential( RequestUri.ToString(), UserName, Password); HttpClient httpClient = new HttpClient(filter); 添加OAuth令牌 如果资源需要Bearer令牌,我使用: HttpClient httpClient = new HttpClient(filter); httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue(“Bearer”, token); ServerCredential为null filter.ServerCredential = null 从服务器获得响应 using(httpClient) { […]

使用HttpClient和Web API方法参数发布到Web API最终为空

我正在尝试使用HttpClient POST到Web API。 当我在Web API的Save方法中放置断点时,[FromBody] Product为null。 这意味着我将产品发布到Web API的方式出了问题。 有人可以看看下面的代码,看看我可能会出错。 我假设它与标题和内容类型有关。 POST从客户端存储库调用Web API,它应该通过JSON传递产品对象: public async Task SaveProduct(Product product) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(“http://localhost:99999/”); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); StringContent content = new StringContent(JsonConvert.SerializeObject(product)); // HTTP POST HttpResponseMessage response = await client.PostAsync(“api/products/save”, content); if (response.IsSuccessStatusCode) { string data = await response.Content.ReadAsStringAsync(); product […]

HttpClient和使用代理 – 不断获得407

这是代码: HttpClient client = null; HttpClientHandler httpClientHandler = new HttpClientHandler() { Proxy = new WebProxy(string.Format(“{0}:{1}”, proxyServerSettings.Address, proxyServerSettings.Port),false), PreAuthenticate = true, UseDefaultCredentials = false, }; this.httpClientHandler.Credentials = new NetworkCredential(proxyServerSettings.UserName, proxyServerSettings.Password); this.client = new HttpClient(this.httpClientHandler); 当我最终这样做时: HttpResponseMessage httpResponseMessage = this.client.PostAsync(urlToPost, new StringContent(data, Encoding.UTF8, this.mediaType)).Result; 它总是抛出 远程服务器返回错误:(407)需要代理身份validation。 对于我这个世界,我不明白。 在IE10中配置或者我使用HttpWebRequest类时,相同的代理设置工作正常

在.NET 4.5中找不到HttpClient

我试图在.NET 4.5中使用新的HttpClient ,但Visual Studio抱怨它不存在。 我有System.Net ,但是当我键入System.Net.Http ,它也会抱怨它。 我应该为这个类下载一个新的distributable吗?

通过HttpClient发布文件时,HttpRequest.Files为空

服务器端: public HttpResponseMessage Post([FromUri]string machineName) { HttpResponseMessage result = null; var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0 && !String.IsNullOrEmpty(machineName)) … 客户端: public static void PostFile(string url, string filePath) { if (String.IsNullOrWhiteSpace(url) || String.IsNullOrWhiteSpace(filePath)) throw new ArgumentNullException(); if (!File.Exists(filePath)) throw new FileNotFoundException(); using (var handler = new HttpClientHandler { Credentials= new NetworkCredential(AppData.UserName, AppData.Password, AppCore.Domain) }) […]

HttpClient和SOAP(C#)

我正在尝试使用HttpClient类发送SOAP消息: 使用REST这样做很容易(代码来自这里 ): using System; using System.Net.Http; using System.Json; namespace ConsoleApplication39 { class Program { static void Main(string[] args) { HttpClient proxy = new HttpClient(); proxy.GetAsync(“http://localhost:14892/api/Bloggers”).ContinueWith((r) => { HttpResponseMessage response = r.Result; response.Content.ReadAsAsync().ContinueWith( (a)=> { foreach(var w in a.Result) { Console.WriteLine(w.ValueOrDefault(“Name”).ToString()); Console.WriteLine(w.ValueOrDefault(“Intrest”).ToString()); } }); }); Console.ReadKey(true); } } } 我想用SOAP做类似的事情。 我有主机( http://opensearch.addi.dk/2.2/ )和POST消息的SOAP消息: dc.title=zorro AND […]

使用HttpClient时如何在HttpContent中设置大字符串?

所以,我创建了一个HttpClient并使用HttpClient.PostAsync()发布数据。 我使用了HttpContent HttpContent content = new FormUrlEncodedContent(post_parameters) ; 其中post_parameters是键值对List<KeyValuePair> 问题是,当HttpContent有一个很大的值(一个图像转换为base64要传输)我得到一个URL太长的错误。 这是有道理的 – 因为url不能超过32,000个字符。 但是,如果不是这样,我如何将数据添加到HttpContent ? 请帮忙。