[英]How to make a POST call and send parameters with objective-c in iOS
我添加了使用oauth2在iOS 7应用程序中在LinkedIn上共享文章的功能。 我已经通过身份验证并具有访问令牌。 文档似乎对此非常清楚,但是奇怪的是,实际上发布时,事情变得很模糊并且没有很好的文档记录。 我知道我在这里发布: http : //api.linkedin.com/v1/people/~/shares附加了令牌。
iOS是一个巨大的平台,linkedin非常流行,我以为我缺少明显的东西,但是很多谷歌搜索都显示了相同的旧项目引用。 一个示例使用oauth2并确实使我通过身份验证,但我无法进行任何api调用。 我是否错过了linkedin本身的页面? 我已经阅读了共享API页面,但是当涉及到api调用时,没有关于使用Objective-C的单个示例。 我不想做任何事情,但是我对缺乏信息感到惊讶。
每个示例使用OAMutableRequest,构建字典等都具有相同的代码。 但是他们从不解释这是什么,如何合并该库或其他任何东西,只是奇怪。 这是公认的最佳实践吗,该库在3年内没有更新,因此在弧和其他方面存在错误。 所有代码示例均提及相同的“消费者”属性,而没有讨论如何或为什么需要这样做。 我似乎无法找到如何使用参数linkedin需要在网站上发布内容的方式构建发布请求。 OAMutableRequest是唯一的方法吗? 如果是这样,人们如何对其进行更新? 如果没有,那么如何使用NSURLRequest或更简单的方法构建请求。 非常感谢!
要发布json数据,您可以尝试以下操作
-(void)PostJson {
__block NSMutableDictionary *resultsDictionary;
NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"first title", @"title",@"1",@"blog_id", nil];//if your json structure is something like {"title":"first title","blog_id":"1"}
if ([NSJSONSerialization isValidJSONObject:userDictionary]) {//validate it
NSError* error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
NSURL* url = [NSURL URLWithString:@"www.google.com"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];//use POST
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:jsonData];//set data
__block NSError *error1 = [[NSError alloc] init];
//use async way to connect network
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse* response,NSData* data,NSError* error)
{
if ([data length]>0 && error == nil) {
resultsDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
NSLog(@"resultsDictionary is %@",resultsDictionary);
} else if ([data length]==0 && error ==nil) {
NSLog(@" download data is null");
} else if( error!=nil) {
NSLog(@" error is %@",error);
}
}];
}
}
我使用此代码进行URL调用并通过post发送数据
NSURL *url = [NSURL URLWithString:@"http://[YOUR URL]/comment.php?"];
//The URL where you send the POST
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[req setHTTPMethod:@"POST"]; //Set method to POST
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//Set headers for the data, in this case TEXT
//Valor del post
//NSString *UUID = [[NSUUID UUID] UUIDString];
NSString *postData = [NSString stringWithFormat:@"&id=%@&name=%@&comment=%@", self.postID, userName, messageToPost]; //Send the POST Values
NSLog(@"self.postID == %@", self.postID); //Check the POST data
NSString *length = [NSString stringWithFormat:@"%d", [postData length]];
[req setValue:length forHTTPHeaderField:@"Content-Length"]; //Set the POST length
NSLog(@" tamano: %d", postData.length); //Check the length of the POST to send
[req setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]]; //Send the content to the URL
NSHTTPURLResponse* urlResponse = nil; //Response
NSError *err = [[NSError alloc] init]; //Allocate error
NSData *responseData = [NSURLConnection sendSynchronousRequest:req
returningResponse:&urlResponse
error:&err];
//Guardamos los parametros que obtuvimos en la respuesta
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]; //Save the response as string
NSLog(@"Respueta: %@", responseString); //Check the response
希望这对您有帮助
首先,在#import“ AFAppDotNetAPIClient.m”中创建一个常量,您可以通过导入AFNetworking Framework进行添加,并在.m文件中创建一个常量
static NSString * const AFAppDotNetAPIBaseURLString = @"http://demo.urmart.in/u-ryd/";
用您的网址替换它。
NSString *urlString = @"trip_add.php";
[[AFAppDotNetAPIClient sharedClient] POST:urlString parameters:tripData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSError *error = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
NSString *sucessStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"msg"]];
NSLog(@"%@",dict);
NSLog(@"%@",sucessStr);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
tripData = // insert your Dictionary Here and Make it Work
希望最好的。
-(void)postApiCall:(NSMutableDictionary *)dic urlStr:(NSString *)urlStr response:(NSMutableArray *)response{
NSMutableDictionary *completeDictionary = [NSMutableDictionary new];
[completeDictionary setObject:dic forKey:@"[project name]"];
NSLog(@"completeDictionary==> %@",[completeDictionary description]);
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:completeDictionary options:NSJSONWritingPrettyPrinted error:Nil];
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonDatastr %@",str);
NSURL * serviceUrl = [NSURL URLWithString:urlStr];
NSLog(@"REquest URL >> %@",serviceUrl);
NSLog(@"REquest XML >> %@",str);
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setValue:@"Application/json" forHTTPHeaderField:@"Content-type"];
[serviceRequest setHTTPMethod:@"POST"];
[serviceRequest setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *serviceResponse;
NSError *serviceError;
NSData *responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
if (responseData) {
[self parsePostApiData:responseData responseP:response];
}
else{
// AlertViewClass *a = [[AlertViewClass alloc] init];
// [a showMessage:@"Cannot connect to internet." title:@"Skillgrok"];
}
}
-(void)parsePostApiData:(NSData *)response responseP:(NSMutableArray *)responseP{
id jsonObject = Nil;
NSString *charlieSendString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"ResponseString %@",charlieSendString);
if (response==nil) {
NSLog(@"No internet connection.");
// AlertViewClass *a = [[AlertViewClass alloc] init];
// [a showMessage:@"Cannot connect to internet." title:@"Skillgrok"];
}
else{
NSError *error = Nil;
jsonObject =[NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"Probably An Array");
}
else
{
NSLog(@"Probably A Dictionary");
NSDictionary *jsonDictionary=(NSDictionary *)jsonObject;
NSLog(@"jsonDictionary %@",[jsonDictionary description]);
if (jsonDictionary) {
[responseP addObject:jsonDictionary];
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.