简体   繁体   English

如何将数据从iOS应用发送到HTTP服务器

[英]How to send data from iOS app to http server

如何将一些数据从iOS应用程序中的字符串发送到服务器,PHP脚本会将这些数据写入数据库?

so finaly, I have one code, which works! 最后,我有一个代码可以正常工作!

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];

通过以UTF8Encoding转换此字符串,可以发送它。

Try this code 试试这个代码

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"];  
[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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM