-(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];
}
答案 0 :(得分:2)
当我在浏览器中输入localhost字符串时获取数据 在我的代码中我想要的浏览器
您需要实现委托:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Received response: %@", [response url]); //give you the url. [receivedData setLength:0];
}
当服务器提供足够的数据来创建 NSURLResponse对象,委托收到一个 connection:didReceiveResponse:message。委托方法可以 检查提供的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);