如何将数据从iOS应用程序发送到http服务器
答
所以finaly,我有一个代码,它的作品!
NSString *content = @"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/form.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
+2
这将只是请求,而不是urlRequest – Javier 2013-08-22 00:02:37
+0
什么是PHP代码? – 2014-10-26 20:25:39
答
试试这个代码
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody: jsonData];
[request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
答
通过UTF8Encoding,你可以把它这个字符串转换。
答
[self deviceCheck:@"123" Completetion:^(NSArray *result, NSError *error) {
//Here use result,and check the error
}];
//Method
-(void)deviceCheck:(NSString *)device Completetion:(void (^) (NSArray * result,NSError * error))completion{
NSString *deviceRequestString = [NSString stringWithFormat:@"%@?device=%@",webservice,device];
NSURL *JSONURL = [NSURL URLWithString:deviceRequestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSessionDataTask * dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(data == nil){
completion(nil,error);
return;
}
NSError *myError;
NSArray *tableArray = [[NSArray alloc]initWithArray:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(tableArray,myError);
}];
[dataTask resume];
}
+0
此代码支持iOS9 – 2015-12-08 07:40:28
是喜是它为你工作? – 2013-04-29 08:52:59