【发布时间】:2013-12-19 15:32:48
【问题描述】:
我有这个更新函数,可以将 JSON 数据 POST 到一个 url,我从堆栈溢出问题中得到了大部分 POST 部分。但我有点难以理解它的含义。
这是我的代码:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
string startTime = row.Cells[1].Text;
string endTime = row.Cells[2].Text;
string furnace = row.Cells[4].Text;
long ID = Convert.ToInt64(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
CascadingDropDown cddSubsystem = (CascadingDropDown) row.FindControl("cddSubsystem");
CascadingDropDown cddReason = (CascadingDropDown) row.FindControl("cddReason");
DropDownList ddForcedSched = (DropDownList) row.FindControl("ddEditForcedSched");
TextBox txtComments = (TextBox) row.FindControl("txtEditOperatorComments");
// cascading dropdowns have the selected value formatted like this ReasonCode:::ReasonName
string[] reason = cddReason.SelectedValue.Split(new string[] {":::"}, StringSplitOptions.None);
string[] subsystem = cddSubsystem.SelectedValue.Split(new string[] {":::"}, StringSplitOptions.None);
// get the machine code
string machine = "";
foreach (SorEvent evt in _events)
if (evt.Id == ID)
machine = evt.MachineCode;
// create SorEvent object to post
SorEvent updateSorEvent = new SorEvent()
{
Id = ID,
Furnace = furnace,
StartTime = Convert.ToDateTime(startTime),
EndTime = endTime != " " ? Convert.ToDateTime(endTime) : (DateTime?) null,
MachineCode = machine,
ReasonCode = reason[0],
SubsystemCode = subsystem[0],
ForceScheduleFlag = ddForcedSched.SelectedValue,
OperatorComments = txtComments.Text,
};
// POST to url
string url = @"http://cannot.divulge:3020/this/URL/";
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Accept = "application/json";
req.ContentType = "application/json";
req.Method = "POST";
// build a string with the params and encode it
string data = JsonConvert.SerializeObject(updateSorEvent);
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(data);
// send the request
using (Stream post = req.GetRequestStream())
{
post.Write(bytes, 0, bytes.Length);
}
var response = req.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
// return to non-edit state
GridView1.EditIndex = -1;
SetData();
}
我了解大部分 POST 功能,但我对以下内容感到困惑:
var response = req.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
我知道响应变量从我上面定义的请求中获取响应,然后我从响应中创建一个流并读取它并将其设置为一个名为 content 的变量。
那段代码的目的是表明 url POST 成功了吗?
我知道
post.Write(bytes, 0, bytes.length);
正在做实际的post,所以后面的代码必须是为了确认。
这是我获得代码的地方:POSTing JSON to URL via WebClient in C#
【问题讨论】:
标签: c#