[英]In C# how can I send data from SQL Server to a HTTP request using the POST method?
I have a Windows application and need to send some data to a remote server.我有一个 Windows 应用程序,需要向远程服务器发送一些数据。 I send the data but it sends only one value, so I need to read a table from SQL Server and send all values in that table at once.我发送数据但它只发送一个值,所以我需要从 SQL Server 读取一个表并一次发送该表中的所有值。
The code to send data:发送数据的代码:
private void SaveUser()
{
CN.conn = CN.connection;
CN.cmd = new SqlCommand("SELECT [FULLNAME] FROM STUDENTS", CN.conn);
CN.conn.Close();
CN.conn.Open();
CN.dr = CN.cmd.ExecuteReader();
while (CN.dr.Read())
{
try
{
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["latitude"] = CN.dr[0].ToString();
var response = wb.UploadValues("https://urbanwaste.000webhostapp.com/user/pickup.php", "POST", data);
string responseInString = Encoding.UTF8.GetString(response);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
MessageBox.Show("Successfully");
}
CN.conn.Close();
}
My database table:我的数据库表:
Thank you谢谢
Something like this - I did not build & run it so apologies if it isn't perfect but hopefully it will point you in the right direction像这样的东西 - 我没有构建和运行它,如果它不完美,我很抱歉,但希望它会为你指明正确的方向
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
private class DataToSendModel
{
public string FullName { get; set; }
public string OtherProperty1 { get; set; }
public string OtherProperty2 { get; set; }
}
// async as I have used .NET Core and it is best practice, but you can remove async from everywhere if you want (I would suggest not)
public async Task SaveUser()
{
// Always wrap in a `using` statement to endsure cleanup of connections and resources
using (var conn = new SqlConnection(config.GetConnectionString("SomeConnectionStringConfigName")))
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
// Consider a stored procedure for this
cmd.CommandText = "SELECT FullName, OtherColumn1, OtherColumn2 FROM Students";
conn.Open();
using (var reader = await cmd.ExecuteReaderAsync())
while (reader.Read())
{
var dataToSend = new DataToSendModel
{
FullName = reader["FullName"].ToString(),
OtherProperty1 = reader["OtherColumn1"].ToString(),
OtherProperty2 = reader["OtherColumn2"].ToString()
};
// Don't use this, use HttpClient https://blog.jayway.com/2012/03/13/httpclient-makes-get-and-post-very-simple/
//using (var wb = new WebClient())
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync("https://urbanwaste.000webhostapp.com/user/pickup.ph", new StringContent(JsonConvert.SerializeObject(dataToSend)));
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.