1
-(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";
    }

}

其中startConnection方法如下

- (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];
}
4

1 回答 1

2

当我在浏览器中键入本地主机字符串时,我在浏览器中获取我想要在我的代码中的数据

您需要实现一个委托:

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

当服务器提供了足够的数据来创建一个 NSURLResponse 对象时,委托会收到一个 connection:didReceiveResponse: 消息。委托方法可以检查提供的 NSURLResponse 并确定数据的预期内容长度、MIME 类型、建议的文件名和服务器提供的其他元数据。

编辑:

   //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);
于 2013-04-05T10:06:37.433 回答