2013-04-09 56 views
0

我正在研究需要與Windows服務器共享數據的應用程序。我查看了網絡上的一些示例,並提出了下面列出的實現。雖然iOS代碼和Web服務獨立運行良好,但我不知道如何將它們連接在一起。我所見過的所有例子都沒有顯示網絡服務的URL(或者至少不能讓我弄清楚發生了什麼)。請看看我對ServerURL的價值,並建議它應該是什麼。我相信它應該在某處包含入口點「doSomething」的名稱,但我不知道語法應該是什麼樣子。我試過http://texas/WebSite3/Service.asmx/doSomethinghttp://texas/WebSite3/Service.asmx?op=doSomething,但似乎都沒有工作。請讓我知道是否有任何其他問題。如何從iOS設備發送JSON POST到ASP.NET URL

我認爲,一旦我得到它在我的本地系統上工作,我可以用完整的域名取代德克薩斯州。

這裏是iOS的代碼:

-(void)checkWithServer { 
// Create the POST request payload. 
    NSDictionary *tmp = [[NSDictionary alloc]initWithObjectsAndKeys: 
        @"[email protected]", @"email", 
        @"John Doe", @"name", 
        nil]; 
    NSError *error; 
    NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error]; 

    NSString *serverURL = @"http://texas/WebSite3/Service.asmx"; 

// Create the POST request to the server. 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    [request setValue:[NSString stringWithFormat:@"%d", [postdata length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody:postdata]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    [conn start]; 
} 

下面是它談論的Web服務:

[WebService(Namespace = "http://texas/WebSite3")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class Service : System.Web.Services.WebService 
    { 
     public Service() { 

     //Uncomment the following line if using designed components 
     //InitializeComponent(); 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string doSomething(string msg) 
    { 
     byte[] buffer = GetBytes(msg); 
     XmlReader reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(buffer, System.Xml.XmlDictionaryReaderQuotas.Max); 
     XElement root = XElement.Load(reader); 

     string result = "{\"result\":\"none\"}"; 

     return result; 
    } 

回答

1

隨着Axeva的幫助,這就是我想出的。

的iOS代碼:

-(void)checkWithServer { 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
    NSURL *postURL = [NSURL URLWithString: @"http://texas/WebSite3/Service.asmx/doSomething"]; 
    NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
           @"[email protected]", @"email", 
           @"John Doe", @"name", 
           nil]; 

    NSError *error; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL 
                  cachePolicy: NSURLRequestUseProtocolCachePolicy 
                 timeoutInterval: 60.0]; 

    [request setHTTPMethod: @"POST"]; 
    [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; 
    [request setValue: @"application/json; charset=utf-8" forHTTPHeaderField: @"content-type"]; 
    [request setHTTPBody: jsonData]; 

    [NSURLConnection sendAsynchronousRequest: request 
             queue: queue 
          completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { 
           if (error || !data) { 
            // Handle the error 
           } else { 
            // Handle the success 
           } 
          } 
    ]; 
} 

的Web服務器代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.Web.Script.Services; 
using System.Runtime.Serialization; 
using System.Runtime.Serialization.Json; 
using System.Xml; 
using System.Xml.Linq; 
using System.Data; 
using System.Data.SqlClient; 

[WebService(Namespace = "http://texas/WebSite3")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class Service : System.Web.Services.WebService 
{ 
    public Service() { 

    //Uncomment the following line if using designed components 
    //InitializeComponent(); 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string doSomething(string email, string name) 
    { 
     return "{\"name\": \"" + name + "\", \"email\": \"" + email + "\"}"; 
    } 
} 

顯然,Web服務器是足夠聰明的拉開JSON並指定變量名和電子郵件。

+0

代碼正在工作,但它顯示一個不推薦使用的錯誤:(CompletionHandler已棄用使用NsUrlSession .. – 2016-04-25 05:19:28

0

我不相信有與.NET造成問題的任何魔法。試試這樣的:

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
NSURL *postURL = [NSURL URLWithString: @"http://texas/WebSite3/Service.asmx/doSomething"]; 
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys: 
       @"[email protected]", @"email", 
       @"John Doe", @"name", 
       nil]; 

NSString *postValues = [jsonDict urlEncodedString]; 
NSData *jsonData = [postValues dataUsingEncoding: NSUTF8StringEncoding]; 

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: postURL 
                 cachePolicy: NSURLRequestUseProtocolCachePolicy 
                timeoutInterval: 60.0]; 

[request setHTTPMethod: @"POST"]; 
[request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; 
// [request setValue: @"application/json" forHTTPHeaderField: @"content-type"]; 
[request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"content-type"]; 
[request setHTTPBody: jsonData]; 

[NSURLConnection sendAsynchronousRequest: request 
            queue: queue 
         completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { 
          if (error || !data) { 
           // Handle the error 
          } else { 
           // Handle the success 
          } 
         } 
]; 
+0

Axeva,巨大的進步,但我還沒有。我收到了這條消息。 「無效的Web服務調用,參數缺失值:\ u0027msg \ u0027」。該消息是JSON格式,所以我知道我有98%。我如何告訴它傳入的值是用於msg的?或者我應該在doSomething上有不同的東西? – JSWilson 2013-04-09 16:07:45

+1

自從我做了.NET以來已經有一段時間了,但我認爲您的Web服務正在返回JSON,但需要輸入的表單鍵值對。試試我對上面的源進行的更改。您會看到我將註釋發送格式配置爲JSON的行以及添加行以發送表單編碼數據的行的位置。看看是否有幫助。 – Axeva 2013-04-09 18:01:08

+0

它看起來像'content-type'應該是'application/json'。 – JSWilson 2013-04-09 19:50:59

相關問題