具有标题和内容的HttpClient PostAsync C#

时间:2018-10-02 20:09:33

标签: c# .net xml

我通过传递requestUri和内容来使用HttpClient PostAsync方法,但是得到了非常普通的错误消息:

  

发生一个或多个错误

能不能请我指导。不知道是什么原因造成的。当我在邮递员中使用相同的requestUri和内容时,它会按预期工作。

var client = new HttpClient();
var content = new StringContent(authXML);
content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
client.BaseAddress = new Uri(authorizationUri);
var result = client.PostAsync(authorizationUri, content).Result; //Generic error message "One or more errors occurred"
if (response.IsSuccessStatusCode)
{
    // SUCCESS
    // Do Something
}
else
{
    // ERROR
    // Do Something
}

2 个答案:

答案 0 :(得分:1)

提供的代码示例似乎无法获得响应句柄。我认为您需要获取响应,然后将其应用于结果,如下所示:

string result;
var response = client.PostAsync(authorizationUri, content).Result;
response.EnsureSuccessStatusCode();
result = response.Content.ReadAsStringAsync().Result;

答案 1 :(得分:-1)

您需要等待或等待结果。

编辑: 发生的一个或多个错误是任务的聚集异常。您可能需要内部

import re
from matplotlib import pyplot as plt
import datetime

def month(date):
    if "January" in date:
        return 1
    elif "February" in date:
        return 2
    elif "March" in date:
        return 3
    elif "April" in date:
        return 4
    elif "May" in date:
        return 5
    elif "June" in date:
        return 6
    elif "July" in date:
        return 7
    elif "August" in date:
        return 8
    elif "September" in date:
        return 9
    elif "October" in date:
        return 10
    elif "November" in date:
        return 11
    elif "December" in date:
        return 12
    else:
        pass

messages = open("new.txt","r").read()
dates = []

date_2digits = re.finditer('^[0-9][0-9][A-Z][a-z]*[0-9]{6}[:][0-9]{2}', messages, flags=re.MULTILINE)
date_1digit  = re.finditer('^[0-9][A-Z][a-z]*[0-9]{6}[:][0-9]{2}', messages, flags=re.MULTILINE)

for _ in date_2digits:
    txt = str(_.group(0))
    dates.append((int(txt[-9:-5]),month(txt),int(txt[0:2])))

for _ in date_1digit:
    txt = str(_.group(0))
    dates.append((int(txt[-9:-5]), int(month(txt)), int(txt[0:1])))

dates_dict = {}

for entry in dates:
    date = datetime.date(*entry)
    if date not in dates_dict.keys():
        dates_dict[date]=int(1)
    elif date in dates_dict.keys():
        add = dates_dict[date] + 1
        dates_dict.update({date:add})

x = list(dates_dict.keys())
y = list(dates_dict.values())

#plt.plot_date(x,y,'.')
plt.bar(x,y)
plt.xticks(x, rotation='vertical')
plt.show()