ios 使用 Json 在 Objective C 中发布数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9883081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Post data in Objective C using Json
提问by Praneeta
I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
我正在尝试将数据发布到 PHP Web 服务。
我很熟悉使用查询 $.post 在 html 中执行此操作,但我在目标 C 中尝试此操作非常困难。我尝试了在 stackoverflow 上找到的几个博客和问题。
I finally came up with the following code:
我终于想出了以下代码:
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];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
我也试过:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
我的 Web 服务在发布时创建一个新用户并返回用户 ID。两者都成功地进行了 Web 服务调用(创建了一个新的用户 ID),但是它们没有发布数据,即每次都创建一个空白用户。
如果我遗漏了什么,请告诉我。
Thanks.
谢谢。
My other attempts:
我的其他尝试:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:@"myUrl.. "]];
[request setHTTPMethod:@"POST"];
NSString *postString = @"[email protected]&FirstName=Test";
[request setValue:[NSString
stringWithFormat:@"%d", [postString length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue: FInally, figured out what was wrong. I was using http://mypath?params=123as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
我终于解决了这个问题:最后,弄清楚出了什么问题。我使用http://mypath?params=123作为我的 url。我没有演出完整的网址(在其他语言中从不需要它)。但在这里我需要给 htt://mypath/index.php?params=123
回答by Zalykr
I think you would be better off using the NSJSONSerialization class like this:
我认为你最好使用这样的 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];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
使用字典然后将其转换为 JSON 比像字符串一样创建它更容易。
Good luck!
祝你好运!
[SWIFT 3.0] (update)
[ SWIFT 3.0](更新)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
回答by xda1001
I have run your code, and server side receive all message.
我已运行您的代码,服务器端收到所有消息。
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"[email protected]","FirstName":"test"}
And follow code, if jsonRequest
has Non-ASCII characters, the [jsonRequest length]
will be wrong.
并按照代码,如果jsonRequest
有非ASCII字符,[jsonRequest length]
就会出错。
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen
instead.
你可以strlen
改用。
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
或者
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
回答by Inder Kumar Rathore
Try this one
试试这个
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
回答by Cullen SUN
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"%@posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:@"POST"];
[request addRequestHeader:@"content-type" value:@"application/json"];
[request addRequestHeader:@"User-Agent" value:@"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];