Passing parameters to a JSON web service in Objective C

后端 未结 2 666
不知归路
不知归路 2020-12-15 13:48

I\'m trying to call a webservice method and pass a parameter to it.

Here is my webservice methods:

    [WebMethod]
    [ScriptMethod(ResponseFormat =         


        
相关标签:
2条回答
  • 2020-12-15 14:19

    I have used your code and modified a bit. Please try following first:

     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];
    

    Rest part is same with your code (starting from the line NSError *errorReturned = nil).

    Now normally, this code should work. But if you haven't make the modification below in your web.config, it won't.

    Check if your web.config file includes following lines:

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

    I have solved it this way, hope it works for you too.

    If you need more informations, please refer these 2 following questions:
    . Add key/value pairs to NSMutableURLRequest
    . Request format is unrecognized for URL unexpectedly ending in

    0 讨论(0)
  • 2020-12-15 14:27

    Don't take over control of response stream manually. Just change your webservice method a little as below:

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

    Make sure you add [ScriptMethod(ResponseFormat = ResponseFormat.Json)] if you only want to offer Json in return. But if you dont add this, then your method will be capable of handling both XML and Json request.

    P.S. Make sure your web service class is decorated with [ScriptService]

    0 讨论(0)
提交回复
热议问题