2014-05-12 1 views
0

salut im l'implémentation d'une application iOS qui publie des données au service web RESTFul implémenté dans java jersey.iOS -post les données à java jersery jax-rs service web

Code iOS:

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

    NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Chris", @"name", @"99", @"age", nil]; 

    NSData * JsonData =[NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:nil]; 
    NSString * jsonString= [[NSString alloc] initWithData:JsonData encoding:NSUTF8StringEncoding]; 

    NSMutableData *body = [NSMutableData data]; 
    [body appendData:[[NSString stringWithFormat:@"%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding]]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/testwebservice/submit"]]]; 

    [request setHTTPBody:body]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 

    [NSURLConnection sendAsynchronousRequest: request 
             queue: queue 
          completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error) { 
           if (error || !data) { 
            // Handle the error 

            NSLog(@"Server Error : %@", error); 
           } else { 
            // Handle the success 

            NSLog(@"Server Response :%@",response); 
           } 
          } 
    ]; 

code Java Jersey:

@POST 
    @Path("submit") 
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED) 
    public void postMultivaluedName(MultivaluedMap<String, String> aFormParams) { 
     System.out.println("postMultivaluedName"); 

     System.out.println("Name is " + aFormParams.get("name")); 
     System.out.println("Age is " + aFormParams.get("age")); 
    } 

Le problème que je suis face est que la valeur du nom et de l'âge a reçu le service Web est nul.

cependant, si je modifie iOS d'utiliser ce code, cela fonctionne:

NSString *postString = @"name=chris&age=99"; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

Alors, comment puis-je modifier mon Jersey java pour accepter NSData en utilisant NSDictionary?

Lors du débogage, je remarque également que jsonString a effectivement @"{\n "name":"chris" \n "age":"99" \n }. est-ce supposé avoir \ n dans la chaîne?

Répondre

0

J'ai réussi à le résoudre. La raison pour laquelle le code suivant fonctionne est parce que je définir le type de contenu http à application/x-www-form-urlencoded:

NSString *postString = @"name=chris&age=99"; 
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 

au lieu, définissez le type de contenu à application/json; charset=utf-8