我正在尝试使用 C# 制作 a json call。我尝试创建调用,但没有成功:
public bool SendAnSMSMessage(string message)
{
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
request.ContentType = "application/json";
string json = "{ \"method\": \"send\", "+
" \"params\": [ "+
" \"IPutAGuidHere\", "+
" \"msg@MyCompany.com\", "+
" \"MyTenDigitNumberWasHere\", "+
" \""+message+"\" " +
" ] "+
"}";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(json);
writer.Close();
return true;
}
任何关于如何完成这项工作的建议将不胜感激。
最佳答案
在您的代码中,您没有得到 HttpResponse,因此您不会看到服务器端发回给您的内容。
您需要以类似于获取(发出)请求的方式来获取响应。所以
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\": \"send\", " +
" \"params\": [ " +
" \"IPutAGuidHere\", " +
" \"msg@MyCompany.com\", " +
" \"MyTenDigitNumberWasHere\", " +
" \"" + message + "\" " +
" ] " +
"}";
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
我还在 pennysms 文档中注意到,他们期望内容类型为“text/json”而不是“application/json”。这可能没有什么不同,但值得一试,以防它不起作用。
关于c# - 使用 C# 调用 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4982765/