c# 实现http的post请求设置header并获取json数据保存到mysql数据库。
时间: 2024-02-17 19:03:17 浏览: 19
以下是使用C#实现HTTP POST请求,设置Header并获取JSON数据并保存到MySQL数据库的示例代码:
```csharp
using System;
using System.Net;
using System.IO;
using System.Text;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
namespace HttpPostExample
{
class Program
{
static void Main(string[] args)
{
// 设置POST请求的URL地址
string url = "https://example.com/api/data";
// 设置POST请求的Header
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["Authorization"] = "Bearer your_access_token_here";
// 构造POST请求的JSON数据
string postData = JsonConvert.SerializeObject(new { name = "John", age = 30 });
// 将JSON数据写入请求流中
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// 发送POST请求并获取响应
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// 关闭流
reader.Close();
dataStream.Close();
response.Close();
// 解析JSON数据并保存到MySQL数据库
dynamic data = JsonConvert.DeserializeObject(responseFromServer);
string connectionString = "server=localhost;database=mydatabase;uid=myusername;password=mypassword;";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO mytable (name, age) VALUES (@name, @age)";
command.Parameters.AddWithValue("@name", data.name);
command.Parameters.AddWithValue("@age", data.age);
command.ExecuteNonQuery();
connection.Close();
}
Console.WriteLine("Data saved to database successfully.");
}
}
}
```
在上面的示例代码中,我们首先设置POST请求的URL地址和Header,然后构造POST请求的JSON数据并将其写入请求流中。接下来,我们发送POST请求并获取响应,并将响应的JSON数据解析并保存到MySQL数据库中。最后,我们输出一条消息表示数据已成功保存到数据库中。
请注意,示例代码中使用了Json.NET库来处理JSON数据。如果您没有安装此库,请使用NuGet包管理器安装它。您还需要将MySQL.Data.dll添加到您的项目引用中。