如何从iOS设备向ASP.NET URL发送JSON POST

时间:2013-04-09 14:25:26

标签: asp.net ios json web-services

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

我认为一旦我在本地系统上工作,我就可以用完整的域名替换德克萨斯。

以下是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;
    }

2 个答案:

答案 0 :(得分: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分开并分配变量名称和电子邮件。

答案 1 :(得分:0)

我不相信.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
                           }
                       }
 ];