Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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=me@test.com";

[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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...