我正在尝试创建一个将WebRequest发送到网站的控制台应用程序,以便我可以JSON格式从中获取一些信息。建立请求并尝试获取响应后,我只想简单地打印出数据,但是当我调用httpWebRequest.getResponse()时,它将返回NULL。
我尝试了多种其他方法将数据发送到url,但是这些方法都给我类似404或400错误的信息,等等。这种方法至少不会给我任何错误,只是一个NULL。
以下是我正在使用的API文档的快照(尽管文档尚未完成):
这是我现在拥有的控制台应用程序代码:
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.remot3.it/apv/v27/user/login");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("developerkey", "***KEY***");
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
email = "***EMAIL***",
password = "***PASSWORD***"
});
Console.WriteLine(json);
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadLine();
}
}catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
Console.ReadLine();
}
预期的输出是一些JSON数据,但是我从getResponse()返回了NULL。
答案 0 :(得分:0)
尝试序列化表单中的凭据,并将标头作为该类的参数发送。 检查下面的代码。它不是100%符合您的要求,但至少会帮助您理解您的逻辑。
这是我从这段代码中得到的Json Response。其工作完美。请记住在您的Web请求上添加超时选项,并在完成任务后最后关闭流阅读器和流。请检查此代码。
public static string httpPost(string url, string json)
{
string content = "";
byte[] bs;
if (json != null && json != string.Empty)
{
bs = Encoding.UTF8.GetBytes(json);
}
else
{
bs = Encoding.UTF8.GetBytes(url);
}
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "POST";
if (json != string.Empty)
req.ContentType = "application/json";
else
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Timeout = 30000;
req.ReadWriteTimeout = 30000;
//req.UserAgent = "test.net";
req.Accept = "application/json";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
using (WebResponse wr = req.GetResponse())
{
Stream s = wr.GetResponseStream();
StreamReader reader = new StreamReader(s, Encoding.UTF8);
content = reader.ReadToEnd();
wr.Close();
s.Close();
reader.Close();
}
return content;
}