Post data in Objective C using Json

倾然丶 夕夏残阳落幕 提交于 2019-11-26 07:29:28

问题


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.

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];

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.

Thanks.

My other attempts:

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];

I finally solved the issue: FInally, figured out what was wrong. I was using http://mypath?params=123 as 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


回答1:


I think you would be better off using the NSJSONSerialization class like this:

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.

Good luck!

[SWIFT 3.0] (update)

let tmp = ["email": email,
           "FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData



回答2:


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":"test@test.com","FirstName":"test"}

And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

You can use strlen instead.

NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];

or

[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];



回答3:


Try this one

NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];



回答4:


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];


来源:https://stackoverflow.com/questions/9883081/post-data-in-objective-c-using-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!