2011-02-13 51 views
30

Tôi đang cố gắng thực hiện a json call bằng C#. Tôi đã thực hiện cuộc gọi khi tạo cuộc gọi nhưng không hoạt động:cuộc gọi json với C#

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\", "+ 
        "    \"[email protected]\", "+ 
        "    \"MyTenDigitNumberWasHere\", "+ 
        "    \""+message+"\" " + 
        "    ] "+ 
        "}"; 

    StreamWriter writer = new StreamWriter(request.GetRequestStream()); 
    writer.Write(json); 
    writer.Close(); 

    return true; 
} 

Bất kỳ lời khuyên nào về cách thực hiện công việc này sẽ được đánh giá cao.

+1

Bạn nhận bất kỳ lỗi ? "Thông điệp" của bạn trông như thế nào? Bạn có đang sử dụng khóa API thích hợp không? –

+0

@Drackir - Tôi đang sử dụng Khóa API chính xác (Tôi đã thử nghiệm nó bằng một phiên bản email của api và nó hoạt động). Tôi không nhận được bất kỳ lỗi nào. Tôi chỉ không nhận được tin nhắn văn bản. Thông điệp chỉ là một số văn bản thông báo thử nghiệm đơn giản ("sms thử nghiệm" (nhưng không có dấu ngoặc kép)). – Vaccano

+1

Câu trả lời của bạn ở đâu? Bạn thực hiện một yêu cầu nhưng bạn không sử dụng GetResponseStream? –

Trả lời

38

Trong mã của bạn, bạn không nhận được HttpResponse, vì vậy bạn sẽ không thấy những gì phía máy chủ gửi lại cho bạn.

bạn cần nhận được Phản hồi tương tự như cách bạn nhận (thực hiện) Yêu cầu. Vì vậy,

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\", " + 
         "    \"[email protected]\", " + 
         "    \"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;   
    } 
} 

Tôi cũng lưu ý trong tài liệu về pennysms rằng họ mong đợi loại nội dung "text/json" chứ không phải "application/json". Điều đó có thể không tạo ra sự khác biệt, nhưng đáng để thử trong trường hợp nó không hoạt động.

+0

văn bản/json những gì tôi đang tìm kiếm. Tôi có một dịch vụ nghỉ ngơi và nó luôn luôn trở lại xml vì ứng dụng/json. ??? –

4

Nếu chức năng của bạn nằm trong một bộ điều khiển MVC u có thể sử dụng mã dưới đây với một đối tượng từ điển của những gì bạn muốn chuyển đổi sang json

Json(someDictionaryObj, JsonRequestBehavior.AllowGet); 

Cũng thử và nhìn vào system.web.script.serialization.javascriptserializer nếu bạn đang sử dụng .net 3.5

như đối với yêu cầu web của bạn ... nó có vẻ ok ở cái nhìn đầu tiên ..

tôi sẽ sử dụng một cái gì đó như thế này ..

public void WebRequestinJson(string url, string postData) 
    { 
    StreamWriter requestWriter; 

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 
    if (webRequest != null) 
    { 
     webRequest.Method = "POST"; 
     webRequest.ServicePoint.Expect100Continue = false; 
     webRequest.Timeout = 20000; 

     webRequest.ContentType = "application/json"; 
     //POST the data. 
     using (requestWriter = new StreamWriter(webRequest.GetRequestStream())) 
     { 
      requestWriter.Write(postData); 
     } 
    } 
} 

Có thể bạn có thể đặt chuỗi và chuỗi json thành thông số và sử dụng tham số này làm phương thức webrequest chung cho tất cả các cuộc gọi.

+0

Điểm của điều này là gì: 'var webRequest = System.Net.WebRequest.Create (url) là HttpWebRequest;' tại sao không chỉ: 'HttpWebRequest webRequest = System.Net.WebRequest.Create (url);'? –

+4

@Drackir, WebRequest là một lớp trừu tượng. Đó là (tĩnh) Phương thức tạo (về cơ bản là một phương thức Factory) tạo ra một cá thể của lớp thích hợp tùy thuộc vào lược đồ Uri. Có nghĩa là nếu lược đồ Uri được xác định là "http", thì nó tạo ra như là thể hiện của HttpWebRequest. Nếu nó là "ftp" nó sẽ tạo ra một thể hiện của FtpWebRequest. Bằng cách thực hiện "as", biến webRequest biến được đánh máy là một cá thể của HttpWebRequest và vì vậy các thuộc tính và phương thức cụ thể cho lớp đó sẽ có sẵn. Điều đó có ý nghĩa? Tôi sẽ gọi httpWebRequest biến (chỉ để được rõ ràng hơn). –

+0

Đây là tài liệu MSDN cho việc này, chỉ trong trường hợp. http://msdn.microsoft.com/en-us/library/bw00b1dc.aspx –

7

chỉ tiếp tục những gì @Mulki thực hiện với mã của mình

public string WebRequestinJson(string url, string postData) 
{ 
    string ret = string.Empty; 

    StreamWriter requestWriter; 

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 
    if (webRequest != null) 
    { 
     webRequest.Method = "POST"; 
     webRequest.ServicePoint.Expect100Continue = false; 
     webRequest.Timeout = 20000; 

     webRequest.ContentType = "application/json"; 
     //POST the data. 
     using (requestWriter = new StreamWriter(webRequest.GetRequestStream())) 
     { 
      requestWriter.Write(postData); 
     } 
    } 

    HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse(); 
    Stream resStream = resp.GetResponseStream(); 
    StreamReader reader = new StreamReader(resStream); 
    ret = reader.ReadToEnd(); 

    return ret; 
} 
6

Dưới đây là một biến thể của câu trả lời Shiv Kumar, sử dụng Newtonsoft.Json (aka Json.NET):

public static bool SendAnSMSMessage(string message) 
{ 
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc"); 
    httpWebRequest.ContentType = "text/json"; 
    httpWebRequest.Method = "POST"; 

    var serializer = new Newtonsoft.Json.JsonSerializer(); 
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
    { 
     using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter)) 
     { 
      serializer.Serialize(tw, 
       new {method= "send", 
         @params = new string[]{ 
          "IPutAGuidHere", 
          "[email protected]", 
          "MyTenDigitNumberWasHere", 
          message 
         }}); 
     } 
    } 
    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;   
    } 
} 
Các vấn đề liên quan