Post Json data to server in iOS


-(void)webservice{

NSString *url= SERVER_URL;

NSLog(@”url is %@”,url);

 

NSMutableURLRequest *_request = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:url]

cachePolicy:NSURLRequestUseProtocolCachePolicy

timeoutInterval:30.0];

 

NSMutableDictionary *post=[[NSMutableDictionaryalloc] init];

[post setObject:_emailText.text forKey:@”username”];

[post setObject:_passText.text forKey:@”password”];

 

NSError *error;

NSData *data=[NSJSONSerializationdataWithJSONObject: post options:kNilOptionserror:&error];

NSString *jsonString = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

NSString *post = [NSString stringWithFormat:@”json=%@”, jsonString];

NSData*postData = [post dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:NO];

 

NSLog(@”string is %@”,post);

[_request setHTTPMethod:@”POST”];

[_request setValue:@”application/x-www-form-urlencoded”forHTTPHeaderField:@”content-type”];

[_request setHTTPBody:postData];

 

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:_request delegate:self];

[connection start];

 

}

 

 

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

if ([challenge previousFailureCount] == 0) {

NSLog(@”received authentication challenge”);

NSURLCredential *newCredential = [NSURLCredentialcredentialWithUser:@”tylerhorne”

password:@”m2n1shlko”

persistence:NSURLCredentialPersistenceForSession];

NSLog(@”credential created”);

[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

NSLog(@”responded to authentication challenge”);

}

else {

NSLog(@”previous authentication failure”);

}

}

 

 

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

 

}

 

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

// Append the new data to receivedData.

// receivedData is an instance variable declared elsewhere.

 

NSDictionary *response=[NSJSONSerializationJSONObjectWithData:data options:kNilOptionserror:nil];

NSLog(@”response %@”,response);

 

}

 

 

 

– (void)connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error

{

 

NSLog(@”Connection failed! Error – %@ %@”,

[error localizedDescription],

[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: