我正在尝试从C#项目创建一个关于Meetup的事件。我正在尝试使用this API method。
我已经尝试了很多东西,现在我已经把它剥掉了尽可能简单。我的问题是,当我发送请求时,我收到错误请求,并显示“名称是必需的”错误消息。我错过了什么?
以下是相关位:
var address = await GetAddressAsync(apiPath);
// address is like: http://api.meetup.com/{groupID}/events?sign=true&key={API key}
var request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/json";
var json = "{name: \"Tenshiko's Test Event\"}"; //JsonConvert.SerializeObject(requestObject);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
}
try
{
WebResponse response = await request.GetResponseAsync();
var dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseString = reader.ReadToEnd();
var model = JsonConvert.DeserializeObject<TResponse>(responseString);
reader.Close();
dataStream.Close();
response.Close();
return model;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
}
}
}
修改 我尝试按照建议将“&amp; name = something”添加到地址中,并且它有效......但是,问题还没有解决。事件已创建,但其余数据(我作为json发送)仍然无法通过。
答案 0 :(得分:0)
似乎StreamWriter没有向您的POST请求添加任何数据,请尝试这样的事情:
var address = await GetAddressAsync(apiPath);
// address is like: http://api.meetup.com/{groupID}/events?sign=true&key={API key}
var json = "{name: \"Tenshiko's Test Event\"}";
var encoding = new ASCIIEncoding ();
var byte1 = encoding.GetBytes(json);
var request = WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byte1.Length;
using (var reqstream = new request.GetRequestStream())
{
reqstream.Write(byte1, 0, byte1.Length);
}
try
{
WebResponse response = await request.GetResponseAsync();
var dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseString = reader.ReadToEnd();
var model = JsonConvert.DeserializeObject<TResponse>(responseString);
reader.Close();
dataStream.Close();
response.Close();
return model;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
}
}
}