【问题标题】:Unable to post data through HttpClient PostAsync无法通过 HttpClient PostAsync 发布数据
【发布时间】:2013-06-05 08:18:15
【问题描述】:

我正在使用 HttpClient 通过 C# 控制台应用程序使用 post 将数据发送到服务器。 HttpClient PostAsync 无法发布我尝试以各种格式发送的数据 即字符串内容,二进制内容,流内容,通过字典对象的http内容,但帖子为空,服务器返回请求无效异常下面是我的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Web;


namespace ConsoleApplication1
{
    class Program
    {
        string str = ""; int j = 0;
        static void Main(string[] args)
        {
            Program df = new Program();

            df.Started();

        }


         public async void Started()
         {
             string contentLength="0";
             try
             {
                 contentLength = await AccessTheWebAsync();
             }
             catch (Exception e)
             {

             }


             Console.WriteLine(contentLength);
         }

        async Task<string> AccessTheWebAsync()
        {  
            HttpClient client = new HttpClient();

            string token =  "qwerty1234";
            string test = "1";
            string postrequest = "<?xml version='1.0' encoding='UTF-8'?>" +
                              "<request> " +
                              "<rec>asdf1234</rec> " +
                              " <lid>9876</lid> " +
                              "</request> ";


            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("token", token);
            dict.Add("test", test);
            dict.Add("request", postrequest);

            HttpContent content = new FormUrlEncodedContent(dict);

            Uri url = new Uri("http://example.com/"); 

            Task<HttpResponseMessage> getStringTask = client.PostAsync(url, content);    

            HttpResponseMessage httpmesssage = await getStringTask;
            Stream respons = await httpmesssage.Content.ReadAsStreamAsync();
            StreamReader sr = new StreamReader(respons);
            string response =  sr.ReadToEnd();
            return response;

        }



        }

}

提前致谢

【问题讨论】:

  • 您是否通过 Wireshark 或 Fiddler 查看了 HTTP 级别发生的情况?

标签: c# .net asynchttpclient


【解决方案1】:

在控制台应用程序中,您需要等待操作完成,可以使用Task.WaitConsole.ReadKey 或类似方法。另外,避免async void

static void Main(string[] args)
{
    Program df = new Program();
    df.StartedAsync().Wait();
}

public async Task StartedAsync()

【讨论】:

  • 我试过了,但这对我不起作用我得到了同样的无效请求异常
  • 请使用异常详细信息编辑您的问题,包括堆栈跟踪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
相关资源
最近更新 更多