Pra*_*eta 28 post json objective-c nsurlconnection ios
我试图将数据发布到PHP Web服务.
我很熟悉使用查询$ .post在html中执行此操作但我在目标C中尝试此操作时非常难过.我尝试了在stackoverflow上找到的几个博客和问题.
我终于想出了以下代码:
NSString *jsonRequest = [NSString stringWithFormat:@"{\"Email\":\"%@\",\"FirstName\":\"%@\"}",user,fname];
NSLog(@"Request: %@", jsonRequest);
NSURL *url = [NSURL URLWithString:@"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
我也尝试过:
NSURLConnection*connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
我的Web服务在post上创建一个新用户并返回userID.两者都成功进行Web服务调用(创建了新的userID),但是它们不发布数据,即每次都创建一个空白用户.
请告诉我我是否遗漏了什么.
谢谢.
我的其他尝试:
NSMutableURLRequest *request = 
[[NSMutableURLRequest alloc] initWithURL:
 [NSURL URLWithString:@"myUrl.. "]];
[request setHTTPMethod:@"POST"];
NSString *postString = @"Email=me@test.com&FirstName=Test";
[request setValue:[NSString 
                   stringWithFormat:@"%d", [postString length]] 
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString 
                      dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] 
 initWithRequest:request delegate:self];
我终于解决了这个问题:FInally,弄清楚出了什么问题.我使用http:// mypath?params = 123作为我的网址.我没有完整的网址(从不需要其他语言).但在这里我需要给htt://mypath/index.php?params = 123
Zal*_*ykr 40
我认为你最好使用NSJSONSerialization类,如下所示:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     email, @"Email",
                     fname, @"FirstName",
                     nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
使用字典然后将其转换为JSON比创建字符串更容易.
祝好运!
[ SWIFT 3.0 ](更新)
let tmp = ["email": email,
           "FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
试试这个
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
| 归档时间: | 
 | 
| 查看次数: | 70418 次 | 
| 最近记录: |