I'm trying to call a webservice method and pass a parameter to it.
Here is my webservice methods:
[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();
}
Here is my objective c code:
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
}
So when I call GetHelloWorld it works great and:
NSLog(@"%@", retVal);
display HelloWorld, but how do I call GetHelloWorldWithParam ? How to pass a parameter ?
I try with:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"myParameter" forKey:@"param"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
and add the two following lines to the request:
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];
I have the error :
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()
Thank you for your help!
Teddy
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…