【问题标题】:How do I send a JSON POST from an iOS device to an ASP.NET URL如何将 JSON POST 从 iOS 设备发送到 ASP.NET URL
【发布时间】:2013-04-09 14:25:25
【问题描述】:

我正在开发一个需要与 Windows 服务器共享数据的应用程序。我查看了网络上的一些示例,并提出了下面列出的实现。虽然 iOS 代码和 Web 服务可以独立工作,但我不知道如何将它们连接在一起。我看到的所有示例都没有显示 Web 服务的 URL(或者至少没有以让我弄清楚发生了什么的方式)。请查看我对 ServerURL 的值并建议它应该是什么。我相信它应该在某处包含入口点“doSomething”的名称,但我不知道语法应该是什么样子。我尝试过http://texas/WebSite3/Service.asmx/doSomethinghttp://texas/WebSite3/Service.asmx?op=doSomething,但似乎都不起作用。如果还有其他问题,请告诉我。

我假设一旦我让它在我的本地系统上运行,我就可以用完整的域名替换 Texas。

这是 iOS 代码:

-(void)checkWithServer {
// Create the POST request payload.
    NSDictionary *tmp = [[NSDictionary alloc]initWithObjectsAndKeys:
                     @"test@gmail.com", @"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];
}

这是它与之对话的网络服务:

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

【问题讨论】:

    标签: asp.net ios json web-services


    【解决方案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:
                                  @"test@gmail.com", @"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
                                   }
                               }
         ];
    }
    

    网络服务器代码:

    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 + "\"}";
        }
    }
    

    显然,网络服务器足够聪明,可以将 JSON 分开并分配变量名称和电子邮件。

    【讨论】:

    • 代码正在运行,但它显示一个已弃用的错误:( CompletionHandler 已弃用使用 NsUrlSession ..
    【解决方案2】:

    我不相信 .NET 有什么魔力会导致这些问题。试试这样的:

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSURL *postURL = [NSURL URLWithString: @"http://texas/WebSite3/Service.asmx/doSomething"];
    NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                     @"test@gmail.com", @"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
                               }
                           }
     ];
    

    【讨论】:

    • Axeva,向前迈出了一大步,但我还没到那一步。我收到这条消息。 “无效的 Web 服务调用,缺少参数值:\u0027msg\u0027”。该消息是 JSON 格式的,所以我知道我在那里 98%。我如何告诉它传入的值是用于 msg 的。还是我应该在 doSomething 中有一些不同的东西?
    • 自从我使用 .NET 已经有一段时间了,但我认为您的 Web 服务正在返回 JSON,但需要表单键值对作为输入。试试我对上面源代码所做的更改。您将看到我在哪里注释掉了将发送格式配置为 JSON 的行,以及我在哪里添加了该行以发送表单编码数据。看看有没有帮助。
    • 看起来content-type 应该是application/json
    • 好的。这就是我原来的样子。
    • 知道为什么我在 iOS 中得到的响应是:{"d": "{\"name\": \"John Doe\", \"email\": \"test@gmail.com\"}"}“d”从何而来?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多