Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

iphone - How to post data through json in iOS

I have attempted to post data into server through json. Suppose i have just one field named username into my xib. Now i am posting this data into server. I have written this code NSString *uname=txt_name.text;

NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:
 [NSURL URLWithString:@"http://mypath/index.php?params=123"]];

[request setHTTPMethod:@"POST"];

// NSString *postString = @"[email protected]";

[request setValue:[NSString
                   stringWithFormat:@"%d", [uname length]]
forHTTPHeaderField:@"Content-length"];

[request setHTTPBody:[uname
                      dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc]
 initWithRequest:request delegate:self];

NSLog(@"text",uname);

But i do not know the data is posting or not. I want to post my input data into console of in Xcode but there nothing is showing. What the reason..? Whats wrong is going on..?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need the following request:

NSDictionary *dataDict = @{@"uname": <YOUR_UNAME>};

NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];

NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://mypath/index.php?params=123"]];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:@"%d",postData.length] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

To ensure the server have got your data use

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSInteger statusCode = httpResponse.statusCode;
    ...........
}

In case of success you will get statusCode = 200.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...