2013-02-13 4 views
3

J'ai un service Web asp.net simple qui renvoie des données au format json. Je veux envoyer une requête http avec paramètre pour obtenir des données json. Comment puis-je envoyer une requête et obtenir des données?Http Post demande avec des paramètres

demande de poste:

POST /JsonWS.asmx/FirmaGetir HTTP/1.1 
Host: localhost 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 

firID=string 

réponse:

HTTP/1.1 200 OK 
Content-Type: text/xml; charset=utf-8 
Content-Length: length  
<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">string</string> 

J'essaie des codes, mais ils ne fonctionnent pas.

NSString *firmadi [email protected]""; 
NSMutableData *response; 


-(IBAction)buttonClick:(id)sender 
{ 
    NSString *firid = [NSString stringWithFormat:@"800"]; 

    response = [[NSMutableData data] retain]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"]]; 

    NSString *params = [[NSString alloc] initWithFormat:@"firID=%@",firid]; 
    [request setHTTPMethod:@"POST"]; 
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if(theConnection) 
    { 
     response = [[NSMutableData data] retain]; 

    } 
    else 
    { 
     NSLog(@"theConnection is null"); 
    } 

} 

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)responsed 
{ 
    [response setLength:0]; 
    NSURLResponse * httpResponse; 

    httpResponse = (NSURLResponse *) responsed; 

} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data 
{ 
    [response appendData:data]; 
    //NSLog(@"webdata: %@", data); 

} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError*)error 
{ 
    NSLog(@"error with the connection"); 
    [connection release]; 
    [response release]; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 

    response = [[NSMutableData data] retain]; 

NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 

} 
+1

Avez-vous essayé de définir le type MIME sur la requête 'application/json' au lieu de 'application/x-www-form-urlencoded'? –

+0

Cela vient de mon service web, pourquoi je change ce paramètre? –

+0

Qu'est-ce qui n'a pas fonctionné avec le code que vous avez publié? –

Répondre

1

Que faites-vous ici:

[[NSURLConnection alloc] initWithRequest:request delegate:self]; 

Cette ligne retourne un NSURLConnection mais vous n'êtes pas le ranger. Cela ne fait rien pour vous.

Vous effacez vos données avant de le lire:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    response = [[NSMutableData data] retain]; // This line is clearing your data get rid of it 
    NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 

} 

Modifier

-(IBAction)buttonClick:(id)sender { 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.23/testService/JsonWS.asmx?op=FirmaGetir"] 
                  cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData 
                 timeoutInterval:15]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:[@"firID=800" dataUsingEncoding:NSUTF8StringEncoding]]; 
    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [self.connection start]; 

} 


#pragma NSURLConnection Delegates 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 

    if (!self.receivedData){ 
     self.receivedData = [NSMutableData data]; 
    } 
    [self.receivedData appendData:data]; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    NSString *responseString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; 
    NSLog(@"%@",responseString); 
} 
+0

Merci de votre attention. Im nouveau au développement d'ios. Par conséquent, il y a un bloc de code stupide dans mon code. Je pose des questions pour cette raison. Je vais essayer ceux-ci, mais s'il vous plaît écrivez le code complet de ce processus. –

+0

J'ai ajouté un exemple de code. – Jaybit

+0

Merci, je vais essayer demain. –

0

Je souffrais de ce problème ce matin et je figure juste maintenant. Je suppose que la clé de votre question est Comment utiliser la méthode POST avec le paramètre. En fait, c'est assez simple.

(1) Tout d'abord, assurez-vous que votre fichier est prêt à être envoyé. Ici, nous disons que c'est un NSString appelé stringReady. Nous l'utilisons comme paramètre dans notre méthode appelée postRequest (Ici, nous ne voulons pas parler du paramètre HTTP POST, ne vous inquiétez pas).

// Send JSON to server 
- (void) postRequest:(NSString *)stringReady{ 
// Create a new NSMutableURLRequest 
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.xxxxxx.io/addcpd.php"]]; 
[req setHTTPMethod:@"POST"]; 

(2) Maintenant, nous disons que le paramètre que le serveur veut obtenir que l'on appelle des « données », c'est la façon comment insérer votre paramètre au corps HTTP.

// Add the [data] parameter 
NSString *bodyWithPara = [NSString stringWithFormat:@"data=%@",stringReady]; 

Voir, il est comment ajouter un paramètre lors de l'utilisation de la méthode POST. Vous venez de mettre simplement le paramètre avant le fichier que vous souhaitez envoyer. Si vous aleary konw ce que votre paramètre alors vous pouvez mieux consulter ce site Web:

https://www.hurl.it/

Cela vous aidera à tester si vous envoyez des fichiers correctement et il affichera la réponse au fond du site.

(3) Troisièmement, nous emballons notre NSString à NSData et l'envoyons au serveur.

// Convert the String to NSData 
NSData *postData = [bodyWithPara dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
// Set the content length and http body 
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]]; 
[req addValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[req setHTTPBody:postData]; 
// Create an NSURLSession 
NSURLSession *session = [NSURLSession sharedSession]; 
NSURLSessionDataTask *task = [session dataTaskWithRequest:req 
             completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 
              // Do something with response data here - convert to JSON, check if error exists, etc.... 
              if (!data) { 
               NSLog(@"No data returned from the sever, error occured: %@", error); 
               return; 
              } 

              NSLog(@"got the NSData fine. here it is...\n%@\n", data); 
              NSLog(@"next step, deserialising"); 

              NSError *deserr; 
              NSDictionary *responseDict = [NSJSONSerialization 
                      JSONObjectWithData:data 
                      options:kNilOptions 
                      error:&deserr]; 
              NSLog(@"so, here's the responseDict\n\n\n%@\n\n\n", responseDict); 
             }]; 

[task resume];} 

Espérons que cela peut aider quelqu'un qui reste coincé ici.