JSON调用用C# [英] json call with C#

查看:136
本文介绍了JSON调用用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个JSON调用使用C#。我创造一个电话做了一个尝试,但它没有工作:

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

这是如何使这项工作将AP preciated任何意见。

Any advice on how to make this work would be appreciated.

推荐答案

在您的code你没有得到的Htt presponse,所以你不会看到什么服务器端发送你回来。

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

我也注意到,他们希望文/ JSON,而不是应用/ JSON的内容类型pennysms文档中获得。这可能不会有所作为,但它是值得一试的情况下,这是行不通的。

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.

这篇关于JSON调用用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆