每當我嘗試發佈一些東西到我的PHP服務器,我收到以下消息。好像代碼連接到服務器,但沒有數據被返回,並且發佈數據沒有經過。它通過我製作的Java應用程序工作,所以我可以保證他們對我的PHP沒有任何問題。如果你能幫助我,或者需要更多的代碼來幫助我,那就問問它。謝謝。NSURLConnection連接到服務器,但不發佈數據
這裏是準備我的變量爲NSURLConnection的代碼:
NSString *phash = [NSString stringWithFormat:@"%d",phashnum];
[phash stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
name = _nameField.text;
[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
email = _emailField.text;
[email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
這裏是我的NSURLConnection的代碼:
NSString *urlPath = [NSString stringWithFormat:@"http://54.221.224.251"];
NSURL *url = [NSURL URLWithString:urlPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
NSOperationQueue *queue= [[NSOperationQueue alloc]init];
NSString *postData = [[NSString alloc] initWithString:stringdata];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length] > 0 && connectionError==nil){
NSLog(@"Connection Success. Data Returned");
NSLog(@"Data = %@",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if([data length] == 0 && connectionError == nil){
NSLog(@"Connection Success. No Data returned.");
NSLog(@"Connection Success. Data Returned");
NSLog(@"Data = %@",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if(connectionError != nil && connectionError.code == NSURLErrorTimedOut){
NSLog(@"Connection Failed. Timed Out");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if(connectionError != nil)
{
NSLog(@"%@",connectionError);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
}];
在此先感謝。
使用AFNetworking,它使你的生活變得更加簡單! https://github.com/AFNetworking/AFNetworking –