HTTP POST请求方法未执行。如何使用httpclient?
我正在尝试使用httpclient提出发布请求。我要发布的预期JSON存储在var Result
中,看起来像:
{
"ID": 142,
"StationNo": 19,
"RunTime": 1800,
"ControllerID": 4,
"ControllerAddress": 2,
"ProgramNo": 5,
"ModeID": "AutoProgram",
"EventDate": "2022-04-27T22:30:02",
"Description": "Irrigation Completed",
"MessageCode": 5,
"time": "2022-05-06T08:58:41.322Z",
"source": {
"id": "43432088"
},
"type": "c8y_Golf_Controller",
"text": "PilotCC Data New Msg"
}
foreach循环运行4次迭代,但没有成功的请求。它只是什么都没有回应。我已经在Postman中测试了上述JSON,在那里工作正常。
这是我的示例代码:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Net.Mime;
using System.Net.Http.Json;
namespace ObjFromJson
{
public class Program
{
static async Task Main(string[] args)
{
string json = @"{
'Values': [
{
'MsgSource': null,
'TagName': 'Data.New_MSG',
'RawValue': '[\r\n {\r\n \'ID\': 145,\r\n \'StationNo\': 6,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 2,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T23:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 144,\r\n \'StationNo\': 18,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:00\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 143,\r\n \'StationNo\': 15,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 4,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 142,\r\n \'StationNo\': 19,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n }\r\n]',
'ScaledValue': '[\r\n {\r\n \'ID\': 145,\r\n \'StationNo\': 6,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 2,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T23:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 144,\r\n \'StationNo\': 18,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:00\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 143,\r\n \'StationNo\': 15,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 4,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 142,\r\n \'StationNo\': 19,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n }\r\n]',
'Status': 'Normal',
'ComStatus': null,
'TimeStamp': '2022-04-28 13:17:39.851'
}
]
}";
Root root = JsonConvert.DeserializeObject<Root>(json);
string rawValue = root.Values[0].RawValue;
JArray array = JArray.Parse(rawValue);
string isoTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
string json2 = $"{{\"time\": \"{isoTime}\",\"source\": {{\"id\": \"43432088\" }},\"type\": \"c8y_Golf_Controller\",\"text\": \"PilotCC Data New Msg\"}}";
JObject json3 = JObject.Parse(json2);
var result = new JObject();
foreach(var item in array)
{
result.Merge(item);
result.Merge(json3);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","base64authvalue");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.com.nsn.cumulocity.event+json"));
JsonContent myContent = JsonContent.Create(result);
HttpResponseMessage response = await client.PostAsync("https://myurl.com", myContent);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
}
public class Root
{
public List<Value> Values {get; set;}
}
public class Value
{
public string RawValue { get; set; }
}
}
}
编辑:添加console.write((int)wrespons.statuscode);
在 console.writeline(响应格林);
及其返回错误代码:415
在提出请求时几乎没有重要的事情:
- The Content-Type must be "application/json"
- It must have Accept header with value as "application/vnd.com.nsn.cumulocity.event+json"
- Basic auth must be used
我正在掌握所有这些内容和JSON 变量结果
也以正确的格式(在邮递员中进行了测试),那么我在这里还缺少什么?
I'm trying to make a post request using HttpClient. The expected json which I'm trying to post is stored in var result
and looks like :
{
"ID": 142,
"StationNo": 19,
"RunTime": 1800,
"ControllerID": 4,
"ControllerAddress": 2,
"ProgramNo": 5,
"ModeID": "AutoProgram",
"EventDate": "2022-04-27T22:30:02",
"Description": "Irrigation Completed",
"MessageCode": 5,
"time": "2022-05-06T08:58:41.322Z",
"source": {
"id": "43432088"
},
"type": "c8y_Golf_Controller",
"text": "PilotCC Data New Msg"
}
The foreach loop runs for 4 iterations but no successful request is made. It just returns nothing in response. I've tested the above json in postman and it works fine there.
Here's my sample code :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Net.Mime;
using System.Net.Http.Json;
namespace ObjFromJson
{
public class Program
{
static async Task Main(string[] args)
{
string json = @"{
'Values': [
{
'MsgSource': null,
'TagName': 'Data.New_MSG',
'RawValue': '[\r\n {\r\n \'ID\': 145,\r\n \'StationNo\': 6,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 2,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T23:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 144,\r\n \'StationNo\': 18,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:00\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 143,\r\n \'StationNo\': 15,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 4,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 142,\r\n \'StationNo\': 19,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n }\r\n]',
'ScaledValue': '[\r\n {\r\n \'ID\': 145,\r\n \'StationNo\': 6,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 2,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T23:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 144,\r\n \'StationNo\': 18,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:00\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 143,\r\n \'StationNo\': 15,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 4,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:00:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n },\r\n {\r\n \'ID\': 142,\r\n \'StationNo\': 19,\r\n \'RunTime\': 1800,\r\n \'ControllerID\': 4,\r\n \'ControllerAddress\': 2,\r\n \'ProgramNo\': 5,\r\n \'ModeID\': \'AutoProgram\',\r\n \'EventDate\': \'2022-04-27T22:30:02\',\r\n \'Description\': \'Irrigation Completed\',\r\n \'MessageCode\': 5\r\n }\r\n]',
'Status': 'Normal',
'ComStatus': null,
'TimeStamp': '2022-04-28 13:17:39.851'
}
]
}";
Root root = JsonConvert.DeserializeObject<Root>(json);
string rawValue = root.Values[0].RawValue;
JArray array = JArray.Parse(rawValue);
string isoTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
string json2 = quot;{{\"time\": \"{isoTime}\",\"source\": {{\"id\": \"43432088\" }},\"type\": \"c8y_Golf_Controller\",\"text\": \"PilotCC Data New Msg\"}}";
JObject json3 = JObject.Parse(json2);
var result = new JObject();
foreach(var item in array)
{
result.Merge(item);
result.Merge(json3);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","base64authvalue");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.com.nsn.cumulocity.event+json"));
JsonContent myContent = JsonContent.Create(result);
HttpResponseMessage response = await client.PostAsync("https://myurl.com", myContent);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseString);
}
}
}
public class Root
{
public List<Value> Values {get; set;}
}
public class Value
{
public string RawValue { get; set; }
}
}
}
EDIT : Added Console.Write((int)response.StatusCode);
just beforeConsole.WriteLine(responseString);
and it's returning Error code: 415
There are few important things to consider while making the request :
- The Content-Type must be "application/json"
- It must have Accept header with value as "application/vnd.com.nsn.cumulocity.event+json"
- Basic auth must be used
I'm handeling all these things and the JSON which is in var result
is also in correct format (tested in postman) then what else am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有了更多的研究,一整天都在完成这项工作之后,我终于能够完成它。
至于我在这里提出的这个特定问题,这是因为内容类型变为
application/json; charset = UTF-8
可能会引起不支持的媒体类型错误。我添加了
字符串JSON4 = JSONCONVERT.SerializeObject(result);
result.merge(json3); in foreach loop中的行并更换了行jsoncontent mycontent = jsoncontent。创建(结果);
带有var StringContent = new StringContent(JSON4,ENCODING.UTF8,MEDIATYPENAMES.APPLICATION.JSON); StringContent.Headers.ContentType.Charset =“”;
这将从您的内容类型标题中删除charset。
With a little more research, after spending entire day to make this work I was finally able to get it done.
As for this particular problem which I have raised here, it's because the Content-Type becomes
application/json; charset=utf-8
which can raise unsupported media type error.I added
string json4 = JsonConvert.SerializeObject(result);
afterresult.Merge(json3);
line in foreach loop and replaced the lineJsonContent myContent = JsonContent.Create(result);
withvar stringContent = new StringContent(json4, Encoding.UTF8, MediaTypeNames.Application.Json); stringContent.Headers.ContentType.CharSet = "";
This removes the charset from your Content-Type header.