1.推荐使用AFN的框架提交最简单,网上很多例子这就不说了
2.只提交数据,没实现提交图片
3.说明: 写入的文字数据:一条表单分割符(--BOUNDARY) + "key" + "value" + 一条表单分隔符;
-(void)uploadDataWithUrl2:(NSString *)url{
NSString *urlStr = [NSString stringWithFormat:@"%@%@",APIURL,url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:100];
NSError *error;
NSDictionary *locationDict = @{@"address":self.LastAddress,@"latitude":self.latitude,@"longitude":self.longitude,@"loctype":@"GPS定位"};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:locationDict options:NSJSONWritingPrettyPrinted error:&error];
NSString *data = [[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
//分隔 开始
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
//第一个参数
NSString *dispositions_data = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"locationdata"];
[body appendData:[self getDataWithString:dispositions_data]];
[body appendData:[self getDataWithString:@"\r\n"]];
[body appendData:[self getDataWithString:data]];
[body appendData:[self getDataWithString:@"\r\n"]];
//分隔
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
//第二个参数
NSString *dispositions_clientid = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"clientid"];
[body appendData:[self getDataWithString:dispositions_clientid]];
[body appendData:[self getDataWithString:@"\r\n"]];
[body appendData:[self getDataWithString:self.recommendCode]];
[body appendData:[self getDataWithString:@"\r\n"]];
//分隔
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
//第三个参数
NSString *deviceID = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceID"];
NSString *dispositions_mac = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"mac"];
[body appendData:[self getDataWithString:dispositions_mac]];
[body appendData:[self getDataWithString:@"\r\n"]];
[body appendData:[self getDataWithString:deviceID]];
[body appendData:[self getDataWithString:@"\r\n"]];
//分隔结束
[body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
request.HTTPBody = body;
[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)body.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"multipart/form-data; boundary=BOUNDARY" forHTTPHeaderField:@"Content-Type"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
return ;
}
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result=%@",result);
}];
[dataTask resume];
}
-(NSData *)getDataWithString:(NSString *)string{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return data;
}