I'm sending a POST request to server but they receive it duplicated with the same date and even time. this is my code :
-(void) getTerms{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
User *mUser = [[User alloc]init];
NSString *appFile1 = [self getUserFile];
mUser = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile1];
NSString *post = [NSString stringWithFormat:#"Method=GetFAQ&CustomerID=%#",mUser.customerID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[ServerName serverName]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
[SVProgressHUD dismiss];
if( theConnection ){
// other codes
}
});
});
}
I just wonder what is wrong with my code ? thanks in advance
this is how i solved the problem :
-(void) getCredit{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *post = [NSString stringWithFormat:#"Method=%#",mMethod];
NSMutableURLRequest *request = [ServerName postToServer:post];
dispatch_async(dispatch_get_main_queue(), ^{
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSUTF8StringEncoding];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSDictionary *res1 = [res objectForKey:#"ServerResponse"];
});
});
}
Related
In my app i need to post data to server and need to recieve response. But i am getting null value after posting data.Below is my full code. Thanks in advance.
{
NSString *post =[[NSString alloc] initWithFormat:#"%#%#%#%#%#",[self.username_reg text],[self.emailid_reg text],[self.phone_reg text],[self.password_reg text],[self.confirmpassword_reg text]];
NSLog(#"PostData: %#",post);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url=[NSURL URLWithString:#"https://servlet/URL"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:_username_reg.text forKey:#"UserName"];
[postDict setValue:_emailid_reg.text forKey:#"Email"];
[postDict setValue:_phone_reg.text forKey:#"Phone"];
[postDict setValue:_password_reg.text forKey:#"Pass"];
[postDict setValue:_confirmpassword_reg.text forKey:#"ConPass"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSLog(#"bcbc:%#",requestBodyData);
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"new:%#",newStr);
NSError *error;
NSDictionary *json_Dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",json_Dict);
}];
}
The Request given format is:
{"UserName":"sony","Email":"ronyv#example.in","Phone":"7358700457","Pass":"sony88","ConPass":"sony88"}
The response need to get:
{"responseHeader":{"responseCode":0,"responseMessage":"Success"}}
Try this code:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:#"your dictionary name" options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:requestData];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[body length]];
NSURL *url = [NSURL URLWithString:#"your url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPShouldHandleCookies:NO];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error)
{
if (error) {
failure(error);
} else {
NSDictionary * jsonDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",jsonDic);
if ([jsonDic objectForKey:#"error"]) {
}
else{
}
}
}] resume];
I am new to IOS i need to know how to pass NSString as parameter in nsurlconnection POST method,i passed string but it become empty
viewdidload:
NSString *parseURL =#"http:url";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json1 valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json1 valueForKeyPath:#"Branches.id"];
NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",str);
[self sendDataToServer :#"POST"];
}
post method:
In post method i passed the string as parameter
-(void) sendDataToServer : (NSString *) method{
//NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[post length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if( theConnection ){
// indicator.hidden = NO;
mutableData = [[NSMutableData alloc]init];
}
}
you can do like
arrMsg = [json1 valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json1 valueForKeyPath:#"Branches.id"];
NSString *str = [arrmsg1 componentsJoinedByString:#","];
NSLog(#"%#",str);
// call the method like
[self sendDataToServer :#"POST" params:str];
// create the method like
-(void) sendDataToServer : (NSString *) method params:(NSString *)str{
NSString *post = [NSString stringWithFormat:#"branch_id=%#",str];
.... continue your work
}
I am using two links.First link i created nsaaray for "id".This "id" i need to pass as parameter in nsurlconnection using POST method by second link.i tried lots but i stuck in while passing parameter "id".
nsaaray for id:
- (IBAction)button_drop:(id)sender {
NSString *parseURL =#"first_link";
NSString *encodeurl =[parseURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encodeurl];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data){
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:&error];
arrMsg = [json valueForKeyPath:#"Branches.branch_name"];
arrmsg1 =[json valueForKeyPath:#"Branches.id"];
[_picker2 reloadAllComponents];
}
}
POST method using nsurlconnection:
NSString *Branchid=#"3";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#\n", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if( connection )
{
mutableData = [NSMutableData new];
}
Try to create a "POST" method like this:-
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
Branchid, #"branch_id", nil];
NSString *newRequest = [dict JSONRepresentation];
NSData *requestData = [newRequest dataUsingEncoding:NSUTF8StringEncoding];
//If you are not using SBJsonParser Library then try the following:
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *urlString = #"YOUR URL String";
NSURL *requestURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long) [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
mutableData = [NSMutableData new];
}
Also, You can follow this link if you don't find out the answer working properly:-
Data in POST or GET methods
Send data in POST methods
I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)MessagePost{
NSString * post =[NSString stringWithFormat:#"http://url.com/clients/project_id=%#&user_id=58&question=%#&send_enquiry=Send",[[self.recordchat objectForKey:#"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength=[NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(#"String : %#",returnstring);
if (postdata){
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:#"status"];
NSLog(#"Status dict = %#",latestLoans);
} else{ NSLog(#"Error while posting messages.");}}
instead of writing NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"Username"];
[post setValue:self.passwordField.text forKey:#"Password"];
Try this -
- (IBAction)loginAction:(UIButton *)sender
{
NSDictionary *dictDetails = #{
#"Username" : self.userNameField.text,
#"Password" : self.passwordField.text
};
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required..
Thank you all for your time and support..
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"username"];
[post setValue:self.passwordField.text forKey:#"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(#"JSON Summary: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response Error= %#", response);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Random Output= %#", jsonObject);
[self performSegueWithIdentifier:#"DASHBOARDSEGUE" sender:sender];
}else {
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
the command:
curl -X POST -F "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " -H "Host: 118932.ro" http://118932.ro/dezv/ipa/index.php
This is what I have so far:
url = [NSURL URLWithString:#"http://www.118932.ro/dezv/ipa/index.php"];
NSData *data = [NSJSONSerialization dataWithJSONObject:self.requestData options:0 error:&error];
NSString *bodyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *dataString = [NSString stringWithFormat:#"\"search=%#\"",bodyString];
NSData *dataBody = [dataString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:dataBody];
[request setValue:#"118932.ro" forHTTPHeaderField:#"Host"];
where self.requestData is the following dictionary
self.requestData = #{#"page" : #"1", #"county" : #"18", #"type" : #"J"};
but this doesnt seem to give me any results after I do this
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
Here is the code I use. The -F parameter in cUrl specifies the actual post data, so you may want to use the string "search={\"page\":\"1\",\"county\":\"18\",\"type\":\"J\"} " as is. You should call this code in a background thread as the synchronous call will block the UI.
/**
* Do an HTTP POST request and return the results
*
* #param NSString * url the URL
* #param NSString * post the POST data
*
* #return NSDictionary * a dictionary containing the response, error, and data
*/
+ (NSDictionary *)httpPostRequestWithUrl:(NSString *)url post:(NSString *)post
{
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:30]; // set timeout for 30 seconds
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSMutableDictionary *rc = [[NSMutableDictionary alloc] init];
if ( response )
[rc setObject:response forKey:#"response"];
if ( error )
[rc setObject:error forKey:#"error"];
if ( data )
[rc setObject:data forKey:#"data"];
return (NSDictionary *)rc;
}