2012-04-01 14 views
5

Estoy intentando llamar a un método de servicio web y pasarle un parámetro.Pasar parámetros a un servicio web JSON en el objetivo C

Aquí es mis métodos de servicio 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(); 
    } 

Aquí está mi objetivo código 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   
} 

Así que cuando llamo GetHelloWorld funciona muy bien y: HelloWorld

NSLog(@"%@", retVal); 

pantalla , pero ¿cómo puedo llamar a GetHelloWorldWithParam? Cómo pasar un parámetro?

trato con:

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

y añadir las dos líneas siguientes a la solicitud:

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

tengo el 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() 

Gracias por su ayuda! Teddy

Respuesta

2

He utilizado su código y modificado un poco. Por favor, intente seguir primero:

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

Resto parte es lo mismo con su código (a partir de la línea NSError *errorReturned = nil).

Ahora normalmente, este código debería funcionar. Pero si no ha realizado la modificación a continuación en su web.config, no lo hará.

Comprobar si el archivo incluye web.config siguientes líneas:

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

lo he resuelto esta manera, espero que funcione para usted también.

Si necesita más información, consulte estas 2 preguntas siguientes:
. Add key/value pairs to NSMutableURLRequest
. Request format is unrecognized for URL unexpectedly ending in

+0

Hola, muchas gracias, esa es la solución. Olvidé el parámetro ... Mi web.config ya tenía estas líneas. – user1306602

1

No asuma el control del flujo de respuesta manualmente. Sólo cambia el método de servicio web un poco de la siguiente manera:

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

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

Asegúrese de agregar [ScriptMethod(ResponseFormat = ResponseFormat.Json)] si sólo desea ofrecer a cambio JSON. Pero si no agrega esto, entonces su método será capaz de manejar solicitudes XML y Json.

P.S. Asegúrese de que su clase de servicio web esté decorada con [ScriptService]

+0

Ok gracias, resuelvo mi problema con la solución a continuación. Lo intentaré con solo devolver en lugar de Context.Response.Write (... – user1306602

Cuestiones relacionadas