c# - 使用 C# 调用 json

标签 c# json httpwebrequest

我正在尝试使用 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/

相关文章:

c# - 在 .NET 中使用 Microsoft.Office.Interop.Excel 需要哪些引用资料?

c# - 如何避免 403 Forbidden 响应的 WebException?

c# - 使用 C# 和 C++ 获取重定向信息

android - 如何从 ESHA Research API 调用多个营养信息? (apid.esha.com)

c# - Task.Run 中的全局错误处理

c# - 匿名结构声明

c# - Linq 加入 Group By

json - 无论如何要验证 jsonpath 的语法是否正确?

javascript - 使用 axios 获取本地 JSON 数据时遇到问题

集合的 REST API 帖子的 JSON 响应