我有以下curl命令:
curl -X POST \
-H "X-dadadadad: APITokenInt" \
-F "log=@logfile.log" \
apilink.com
我想在Objective-C代码中执行类似的操作,但不知道如何操作。 Objective-C中上述内容的等价物是什么?
答案 0 :(得分:1)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://rink.hockeyapp.net/api/2/apps/appID/crashes/upload"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"APITokenInt" forHTTPHeaderField:@"X-HockeyAppToken"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
您提到的参数可以在URL请求的正文中设置。
更新 - 表单
如果要发送POST请求并将类型设置为表单,请设置请求的标题,如下所示:
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
更新2 - 多个标题
在您的情况下,您将需要设置多个标头,这可以完成。您可以使用addValue
方法而不是setValue
方法执行此操作,如下所示:
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"APITokenInt" forHTTPHeaderField:@"X-HockeyAppToken"];