我想在我的C#应用程序中进行以下curl调用:我是代码的初学者 **这段代码得到json对facebook上城市的回应包含字符' a'和角色' b'从Facebook图表api我试图让它我有错误请求被中止:连接意外关闭**
private JArray Getcities(string token)
{
try
{
string s1 = "access_token="+Server.UrlEncode(token);
string s2 = "&batch=" + Server.UrlEncode(" [ { \"method\": \"get\", \"relative_url\":\"search?type=adgeolocation&location_types=city®ion_id=3871&country_code=us&limit=3000&q=a\" }, { \"method\": \"get\", \"relative_url\": \"search?type=adgeolocation&location_types=city®ion_id=3871&country_code=us&limit=3000&q=b\" } ]");
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.3/");//make url
httpRequest.Method = "Post";
httpRequest.ContentType = "text/json; charset=utf-8";
byte[] bytedata = Encoding.UTF8.GetBytes(s1 + s2);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata,0,bytedata.Length);
requestStream.Close();
StreamReader reader;
HttpWebResponse httpWebResponse = (HttpWebResponse) httpRequest.GetResponse()
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
}
var apiData = reader.ReadToEnd();
Response.Write(apiData);
var data = JArray.Parse(apiData).ToString();
//var s = data["data"].ToString();
var x = JArray.Parse(data);
return x;
}
答案 0 :(得分:1)
问题在于使用声明
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
}
在using语句结束时,流会被释放,因此当您尝试读取结束时它不再有效。如果你像这样重写它应该有用。
byte[] apiData;
using (var responsestream = httpWebResponse.GetResponseStream())
{
reader = new StreamReader(responsestream, encoding: Encoding.UTF8);
apiData = reader.ReadToEnd();
}
然后在读取所有数据后处理流。