【问题标题】:Passing parameters to a JSON web service in Objective C在 Objective C 中将参数传递给 JSON Web 服务
【发布时间】:2012-04-15 14:50:22
【问题描述】:

我正在尝试调用 Web 服务方法并向其传递参数。

这是我的网络服务方法:

    [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()

感谢您的帮助! 泰迪熊

【问题讨论】:

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


    【解决方案1】:

    不要手动控制响应流。只需将您的网络服务方法稍作更改,如下所示:

    [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 请求。

    附:确保您的网络服务类使用[ScriptService]

    【讨论】:

    • 好的,谢谢,我用下面的解决方案解决了我的问题。我将尝试只返回而不是 Context.Response.Write(...
    【解决方案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>
    

    我已经通过这种方式解决了,希望它也对你有用。

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

    【讨论】:

    • 嘿,非常感谢,这就是解决方案。我忘记了参数...我的 web.config 已经有这些行了。
    猜你喜欢
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2019-05-19
    • 2018-12-06
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多