如何使用承载令牌发布JSon

时间:2019-04-03 06:41:06

标签: c# json api post bearer-token

我能够使用类似的代码和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();

1 个答案:

答案 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并将PostAsyncStringContent对象一起使用。像这样:

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();