2012-04-01 12 views
5

Sto provando a chiamare un metodo webservice e passare un parametro ad esso.Passaggio dei parametri a un servizio Web JSON nell'obiettivo C

Ecco i miei metodi 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(); 
    } 

Ecco il mio codice C Obiettivo:

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   
} 

Così, quando io chiamo GetHelloWorld funziona benissimo e:

NSLog(@"%@", retVal); 

visualizzazione HelloWorld , ma come posso chiamare GetHelloWorldWithParam? Come passare un parametro?

cerco con:

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

e aggiungere le due righe seguenti alla richiesta:

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

ho l'errore:

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

Grazie per il vostro aiuto! Teddy

risposta

2

Ho usato il tuo codice e modificato un po '. Si prega di provare dopo la prima:

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 è lo stesso con il codice (a partire dalla linea NSError *errorReturned = nil).

Ora questo codice dovrebbe funzionare normalmente. Ma se non hai apportato la modifica di seguito nel tuo web.config, non lo farà.

Verificare se il file web.config include seguenti righe:

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

ho risolto in questo modo, spero che funziona anche per te.

Se avete bisogno di maggiori informazioni, si rimanda queste 2 domande seguenti:
. Add key/value pairs to NSMutableURLRequest
. Request format is unrecognized for URL unexpectedly ending in

+0

Hey, grazie mille, questa è la soluzione, ho dimenticato il param ... Il mio web.config aveva già queste righe. – user1306602

1

Non assumere il controllo del flusso di risposta manualmente. Basta cambiare il metodo di webservice un po 'come di seguito:

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

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

Assicurati di aggiungere [ScriptMethod(ResponseFormat = ResponseFormat.Json)] se desideri solo offrire JSON in cambio. Ma se non lo aggiungi, il tuo metodo sarà in grado di gestire sia la richiesta XML che Json.

P.S. Assicurati che la tua classe di servizio Web sia decorata con [ScriptService]

+0

Ok grazie, io risolvo il mio problema con la soluzione qui di seguito. Proverò con un semplice ritorno invece di Context.Response.Write (... – user1306602

Problemi correlati