如何将原始数据发送到API

问题描述 投票:0回答:2

我有一个文本字段,需要将两个数据发送到 API。

    NSString *post =[NSString stringWithFormat:@"val1=%@,val2=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"val1"],val2];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://api.test.com/send"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    
    NSError *error;
    NSURLResponse *response;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"log%@",str);
}
       

我只需将原始数据发送到 API,这是我的代码。请检查并告诉我。

ios objective-c ios7
2个回答
2
投票
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
           //error
}
else
{
           //no error
}

试试这个


0
投票

您是否尝试过将其转换为 NSData 并发送?

换算如下: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];

这将为您提供以字节为单位的数据,然后只需通过正常的网络功能调用将其传递即可。

© www.soinside.com 2019 - 2024. All rights reserved.