【发布时间】:2013-10-22 08:09:31
【问题描述】:
我们有一个使用 Visual Studio 的 C# 项目任务,我们的讲师给了我们这个示例代码,尝试使用 Json 字符串连接来构建某种电子销售点系统。
不幸的是,我不知道他希望我们如何与该服务器通信,因为我们已经编写了大约 2 个月的代码。他给了我们每个人一个访问令牌和 ID,我们必须先将其解析到服务器,然后才能访问,但我不知道它采用什么格式。为了论证,假设 id = "epos3" 和访问令牌 = 123456789
private void button1_Click(object sender, EventArgs e)
{
var request =System.Net.WebRequest.Create("http://ap.hbwd.in//item/{2812748393}") as System.Net.HttpWebRequest;
request.Method = "GET";
request.ContentLength = 0;
string responseContent;
using (var response = request.GetResponse() as System.Net.HttpWebResponse)
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}//end
}
private void button2_Click(object sender, EventArgs e)
{
// Code for request with JSON text body. Note JSON is just a string here.
var request = System.Net.WebRequest.Create("http://ap.hbwd.in/Products") as System.Net.HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("Content-Type", "application/json");
using (var writer = new System.IO.StreamWriter(request.GetRequestStream()))
{
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes("{\n \"store_id\": \"72932\",\n \"access_token\": \"A733BE122\",\n \"cashier_id\": \"12\",\n \"items\": [[\"1\", 1], [\"4\", 2]],\n \"payment\": [[\"cc\", 27.35], [\"ch\", 10.00]],\n}");
request.ContentLength = byteArray.Length;
writer.Write(byteArray);
writer.Close();
}
string responseContent;
using (var response = request.GetResponse() as System.Net.HttpWebResponse)
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
}
}//end
【问题讨论】:
-
你的问题是:我没试过,但你能帮我做作业吗?您尝试了哪些方法,您在哪里遇到了问题?
-
我们有 1 周的时间来做这件事,我周三有考试,我的问题是,当我不知道服务器接受什么或如何接受这些参数时,我打算如何访问数据?
-
在代码中。它接受参数作为 json 对象(查看该编码行,字符串是 json 对象),并且可能以相同的方式返回它。调试,读取 responseContent 的内容。
-
这里为什么不使用 HTTPHandlers 是一个例子:stackoverflow.com/questions/12401239/…
-
我更多地指的是第一个按钮方法,我只是希望能够获取对象