我正在尝试使用C#进行json调用。我在创建呼叫时遇到了麻烦,但没有成功:
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”。这可能没有什么区别,但是如果它不起作用,则值得尝试。