json call with C#

前端 未结 5 1107
醉话见心
醉话见心 2020-12-04 22:08

I am trying to make a json call using C#. I made a stab at creating a call, but it did not work:

public bool SendAnSMSMessage(string message)
{
    HttpWebR         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 22:42

    In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

    you need to get the Response similar to the way you get (make) the Request. So

    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;        
      }
    }
    

    I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

提交回复
热议问题