How I know the the posting data goes correctly

2019-02-27 16:56发布

问题:

-(IBAction)clicked:(id)sender{
    NSString *CIDString = cID.text;

    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/test/?"];
    NSString *postData = [NSString stringWithFormat:@"companyID=%@",CIDString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    [self startConnection:(NSMutableURLRequest *)request];
     if([self.result isEqualToString:@"New Alert"])
    {
        cID.text = @"Scuess";
    }

}

where startConnection method is as follows

- (void)startConnection:(NSMutableURLRequest *)request {

    [self.connection cancel];

    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData = data;
    self.result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"receivedData: %@", [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]);


    self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (self.networkErrorAlert) {
        NSLog(@"connection fail");

    }

    [self.connection start];
}

回答1:

when i am typing the localhost string in the browser im getting data in the browser which i want in the my code

You need to implement a delegate:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"Received response: %@", [response url]); //give you the url.        [receivedData setLength:0];
}

When the server has provided sufficient data to create an NSURLResponse object, the delegate receives a connection:didReceiveResponse: message. The delegate method can examine the provided NSURLResponse and determine the expected content length of the data, MIME type, suggested filename and other metadata provided by the server.

EDIT:

   //if you want something more...you need to do as :
    NSString *contentTypeValue = nil;
    for (NSString *headerKey in [[(NSHTTPURLResponse*)response allHeaderFields] allKeys] ) {
        if([@"content-type" caseInsensitiveCompare:headerKey] == NSOrderedSame ) {
            contentTypeValue = [[(NSHTTPURLResponse*)response allHeaderFields] valueForKey:headerKey];
        }
     }
     NSLog(@"===>%@",contentTypeValue);