将参数传递给Objective C中的JSON Web服务

时间:2012-04-01 20:29:40

标签: objective-c ios json web-services parameters

我正在尝试调用webservice方法并将参数传递给它。

以下是我的网络服务方法:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetHelloWorld()
    {
        Context.Response.Write("HelloWorld");
        Context.Response.End();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void GetHelloWorldWithParam(string param)
    {
        Context.Response.Write("HelloWorld" + param);
        Context.Response.End();
    }

这是我的目标c代码:

NSString *urlString = @"http://localhost:8080/MyWebservice.asmx/GetHelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) 
{
    //...handle the error
}
else 
{
    NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", retVal);
    //...do something with the returned value        
}

因此,当我致电GetHelloWorld时,它的效果非常好:

NSLog(@"%@", retVal);

显示HelloWorld,但如何调用GetHelloWorldWithParam?如何传递参数?

我尝试:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"myParameter" forKey:@"param"];    
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];

并将以下两行添加到请求中:

[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];

我有错误:

System.InvalidOperationException: Missing parameter: test.
   at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
   at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

感谢您的帮助! 玩具

2 个答案:

答案 0 :(得分:2)

我已经使用了你的代码并进行了一些修改。请先尝试一下:

 NSString *urlString = @"http://localhost:8080/MyWebservice.asmx/GetHelloWorldWithParam";
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSString *myRequestString = @"param="; // Attention HERE!!!!
    [myRequestString stringByAppendingString:myParamString];
    NSData *requestData = [NSData dataWithBytes:[myRequestString UTF8String] length:[myRequestString length]];
    [request setHTTPBody: requestData];

休息部分与您的代码相同(从行NSError *errorReturned = nil开始)。

现在通常,此代码应该有效。但是,如果您未在web.config中进行以下修改,则不会。

检查您的web.config文件是否包含以下行:

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>

我已经解决了这个问题,希望它对你也有用。

如果您需要更多信息,请参考以下2个问题:
. Add key/value pairs to NSMutableURLRequest
. Request format is unrecognized for URL unexpectedly ending in

答案 1 :(得分:1)

不要手动接管对响应流的控制。只需更改您的webservice方法,如下所示:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetHelloWorld()
{
    return "HelloWorld";
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetHelloWorldWithParam(string param)
{
    return "HelloWorld" + param;
}

如果您只想提供Json作为回报,请务必添加[ScriptMethod(ResponseFormat = ResponseFormat.Json)]。但是如果你不添加它,那么你的方法将能够处理XML和Json请求。

P.S。确保您的网络服务类使用[ScriptService]

进行修饰