在C#中,如何使用POST方法将数据从SQL Server发送到HTTP请求?
我有一个Windows应用程序,需要向远程服务器发送一些数据。我发送数据,但它只发送一个值,因此我需要从SQL Server读取一个表,并一次性发送该表中的所有值 发送数据的代码:在C#中,如何使用POST方法将数据从SQL Server发送到HTTP请求?,c#,sql,C#,Sql,我有一个Windows应用程序,需要向远程服务器发送一些数据。我发送数据,但它只发送一个值,因此我需要从SQL Server读取一个表,并一次性发送该表中的所有值 发送数据的代码: private void SaveUser() { CN.conn = CN.connection; CN.cmd = new SqlCommand("SELECT [FULLNAME] FROM STUDENTS", CN.conn); CN.conn.Cl
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();
}
我的数据库表:
谢谢你诸如此类的东西-我没有构建和运行它,因此如果它不完美,我深表歉意,但希望它能为你指明正确的方向
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();
}
}
}
}
你试过使用JSON字符串吗?不,我没有试过,那么你应该确定。请告诉一些教程,描述这种方法。我无法测试它,因为我无法访问你的数据或API,但一般要点在那里,应该可以帮助你开始。关键是序列化一个对象并发送它,这意味着您的API将接收所有属性感谢您的努力问题不在于此C#部分,问题在于PHP部分。无论如何,谢谢你@Rob king