我能够使用类似的代码和Bearer令牌进行GET,但似乎无法执行POST。
当我将Json,URL和Bearer Token复制/粘贴到Postman时,它可以正常工作。但是从C#执行此操作时,出现此错误:
“ StatusCode:400,ReasonPhrase:“错误请求”,版本:1.1,内容: System.Net.Http.StreamContent,标头:{传输编码:分块 连接:keep-alive Expect-CT:最大年龄= 604800, report-uri =“ https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct” CF-RAY:4c190ad8ad786539-SYD日期:2019年4月3日,星期三06:38:54 GMT Set-Cookie:__cfduid = dc0232e99fa0fefc0bd728258229dd5d51554273534; expires =星期四,格林尼治标准时间20年4月2日06:38:54;路径= /; domain = .paymentsapi.io; HttpOnly;安全服务器:cloudflare X-Powered-通过:ASP.NET 内容类型:application / json; charset = utf-8}“
有人可以看到我在做什么吗?
先谢谢了。
JsonSerializerSettings jss = new JsonSerializerSettings();
string strValue = JsonConvert.SerializeObject(TestMaster, jss);
lblJSon.Text = strValue; // This Json is valid
ByteArrayContent bytecontent = new ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(strValue));
bytecontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string AccessToken = lblToken.Text;
HttpClient tRequest = new HttpClient();
tRequest.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
Task<HttpResponseMessage> getTask = tRequest.PostAsJsonAsync(new Uri(strURL).ToString(), bytecontent);
HttpResponseMessage urlContents = await getTask;
Console.WriteLine("urlContents.ToString");
lblEDDR.Text = urlContents.ToString();
答案 0 :(得分:2)
PostAsJsonAsync
将您的ByteArrayContent
转换为json对象。您可以像这样直接将PostAsJsonAsync
和以太TestMaster
一起使用:
string AccessToken = lblToken.Text;
HttpClient tRequest = new HttpClient();
tRequest.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
Task<HttpResponseMessage> getTask = tRequest.PostAsJsonAsync(new Uri(strURL).ToString(), TestMaster);
HttpResponseMessage urlContents = await getTask;
Console.WriteLine("urlContents.ToString");
lblEDDR.Text = urlContents.ToString();
或者您将TestMaster
转换为Json并将PostAsync
与StringContent
对象一起使用。像这样:
JsonSerializerSettings jss = new JsonSerializerSettings();
string strValue = JsonConvert.SerializeObject(TestMaster, jss);
lblJSon.Text = strValue; // This Json is valid
StringContent strcontent = new StringContent (strValue);
bytecontent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string AccessToken = lblToken.Text;
HttpClient tRequest = new HttpClient();
tRequest.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
Task<HttpResponseMessage> getTask = tRequest.PostAsync(new Uri(strURL).ToString(), bytecontent);
HttpResponseMessage urlContents = await getTask;
Console.WriteLine("urlContents.ToString");
lblEDDR.Text = urlContents.ToString();