I have a class which is used to get data from my server. The data returned from my server is in JSON. For some reason the didReceiveData won't run at all. I have placed NSLogs inside it to test it but it doesn't do anything?
Here is my code:
+(NSJSONSerialization *) getTask:(id)task_id{
NSString *post = [NSString stringWithFormat:#"&task_id=%#", task_id];
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:[NSString stringWithFormat:#"http://my-server.com/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
NSLog(#"Testing");
}
return json;
}
// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
NSLog(#"test");
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Error: %#", error);
}
Thanks,
Peter
getTask: is a class method, which means the self is the class. Therefore the delegate methods must also be class methods.
But note that you cannot return the received JSON from the getTask: method, because NSURLConnection works asynchronously.
You need to start the connection. Try using the initWithRequest:delegate:startImmediately: method:
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
or, just call the start method:
if(conn){
[conn start];
}
Related
I am calling odata post api having HTTP header filed is "form-data". Below is my code :-
NSURL *restURL = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:restURL];
[request setHTTPMethod: getorpost];
if (jsonData != nil) {
[request setValue:#"application/form-data" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
}
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
responseData = [[NSMutableData alloc] init];
}
And i am getting below response:-
Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details
But, it is working fine in Postman. Can anyone please suggest where is the fault in my code.
Thanks,
Use this
NSURL *url = [NSURL URLWithString:url_str];
NSLog(#"%#",datastring);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSMutableData *requestBody = [[NSMutableData alloc] initWithData:[datastring dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestBody length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestBody];
httpResponse=[[NSHTTPURLResponse alloc]init];
receivedData=[[NSMutableData alloc]init];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(connection)
{
NSLog(#"%# calling with datastring: %#", url, datastring);
}
delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%d", httpResponse.statusCode);
NSLog(#"%#",[httpResponse description]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
receivedData = [[NSMutableData alloc]init];
httpResponse=[[NSHTTPURLResponse alloc]init];
NSLog(#"%#",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSString *retVal = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"retVal=%#",retVal);
}
-(void)ViewDidLoad
{
NSMutableDictionary *postData = [[NSMutableDictionary alloc]init];
[postData setObject:uid forKey:#"id"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postData options:kNilOptions error:nil];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [[NSString alloc]initWithFormat:#"%#",jsonInputString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"YOUR URL "]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];
[request setURL:url];
[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;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *jsonDict;
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"jsonDoct == %#",jsonDict);
}
else
{
NSLog(#"RESONPSE IS NULL");
}
if (error)
{
NSLog(#"error %#",error.description);
}
}
I need to bind parameters in an object and pass the object as a POST request to receive a successful piece of information from an API.
{
customer = {
"auth_token" = "";
"device_id" = 3e708bf1a49cdd06;
"email_address" = "abc#xyz.in";
name = abc;
number = 1234567890;
"resend_token" = true;
};
}
This is the object that I need to send along with the post request. But when I convert it into a string and post it, the entire object becomes the key and the value becomes nil. It gets posted as {"{customer.....}=>nil}.
The object should be posted as
{"customer:
{"auth_token":"","device_id":"3e708bf1a49cdd06","email_address":"abc#xyz.in",
"name":"abc","number":"1234567890","resend_token":"true"}}
This my current attempt:
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
NSString *postString = [[NSString alloc] initWithData:temp encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[request setHTTPMethod:#"POST"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
A lot of the code used here was used without a proper understanding and directly taken from other StackOverflow answers, so please excuse any bad programming practice.
How can I do this? Any help is appreciated. Thank you.
you can try below code.Instead of converting data to string set it as HTTPBody like
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSArray *objects = [[NSArray alloc] initWithObjects:#"",#"3e708bf1a49cdd06",#"abc#xyz.in",#"abc",#"1234567890",#"true", nil];
NSArray *keys = [[NSArray alloc] initWithObjects:#"auth_token",#"device_id",#"email_address",#"name",#"number",#"resend_token", nil];
NSDictionary *tempJsonData = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSDictionary *finalJsonData = [[NSDictionary alloc] initWithObjectsAndKeys:tempJsonData,#"customer", nil];
NSData *temp = [NSJSONSerialization dataWithJSONObject:finalJsonData options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = temp;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
NSError *error = nil; NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Following is the sample code for sending a POST request to server.
-(void)doRequestPost:(NSString*)url andData:(NSDictionary*)data{
requestDic = [NSDictionary dictionaryWithDictionary:data];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:kNilOptions error:nil];
NSString *jsonString=[[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Request Object:\n%#\n",data);
NSLog(#"Request String:\n%#\n",jsonString);
NSMutableURLRequest *theReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[theReq addValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theReq setHTTPMethod:#"POST"];
[theReq addValue:[NSString stringWithFormat:#"%lu",(unsigned long)[jsonString length]] forHTTPHeaderField:#"Content-Length"];
[theReq setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
connection = [NSURLConnection connectionWithRequest:theReq delegate:self];
}
May this help lot and resolve your problem.
NSString *post =[[NSString alloc] initWithFormat:#"id=%d&restaurant_name=%#", restaurnt_Id, _rest_NameTxt.text];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:EDIT_RESTAURANT_API];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[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"];
[request setHTTPBody:postData];
_responseData = [[NSMutableData alloc] init];
[NSURLConnection connectionWithRequest:request delegate:self];
pragma mark - connection methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[_responseData setLength:0];
[_responseCityData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_responseData appendData:data];
[_responseCityData appendData:data];
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return YES;
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[COMMON showErrorAlert:#"Internet Connection Error!"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#" "];
NSLog(#"%#", responseString);
}
Make your task in connectionDidFinishLoading method
This is my code.
- (void)loadData:(NSString *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"connection found---------");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"reciving data---------");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"connection fail---------");
[self.pddelegate connectionError];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"data posting done---------");
[self.pddelegate dataPosted];
}
It is not working if url become bigger and give connection fail in logs.
Like
url=#".......order_details&admin=29&tableid=89&waiter_id=18&items=MzQ6MSwxMToxLDMzOjEsNjc6MSwzOToxLDY5OjEsNTY6MSw2ODoxLDg6MSw1NToxLDYyOjEsNzY6MSw0MToxLDIwOjEsNjE6MQ=="
see this SO post for get type request length What is the maximum length of a URL in different browsers?
for sending big string use POST type request instead of GET type.
We have there are two methods for sending data.
1. GET Method : Which is used for fixed length or limited length of string only.
2. POST Method : Which is used to send more string while comparing get method.
I have given the example Using PostMethod.
NSString *post =[[NSString alloc] initWithFormat:#"%#",YourString];
NSURL *url=[NSURL URLWithString:*#"YourURL like www.google.com"*];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue: #"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
request.timeoutInterval = 60;
NSError *error = nil;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *errStr = _stringEmpty;
#try { errStr = [error localizedDescription]; }#catch (NSException * exception){ }
If any error occur errStr will show the error.
In the past, I have used some URL's that are around 2000 characters in length in iOS with no problem. NSURL, NSURLRequest, and NSURLConnection all managed just fine. If your URL is shorter than that, the problem is probably not due to its length, but instead related to the way the URL is constructed.
Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
I want to use http Get and Post for getting the request and response of certain URL request,
But i dont know how to use them in objective c..
and Which one will come first Get or Post in establishment of connection.?
how to modify the content and post them back to the server..
Can any one please help me?
for get use :
+(NSMutableURLRequest*)getURq_getansascreen:(NSString*)ws_name {
NSLog(#"%#",ws_name);
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:ws_name] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[urlReq setHTTPMethod:#"GET"];
return urlReq;
}
for post use :
+(NSMutableURLRequest*)postURq_getansascreen:(NSString*)ws_name :(NSString*)service {
NSString *tempUrl = domainURL;
NSString *msgLength = [NSString stringWithFormat:#"%d",[ws_name length]];
NSMutableURLRequest *urlReq = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Service=%#",tempUrl,service]] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
[urlReq addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlReq addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[urlReq setHTTPMethod:#"POST"];
[urlReq setHTTPBody: [ws_name dataUsingEncoding:NSUTF8StringEncoding]];
return urlReq;
}
//Call this in view did load as `
WSPContinuous *wspcontinuous = [[WSPContinuous alloc] initWithRequestForThread:[webService getURq_getansascreen:[webService GetDetails:str_filter]] sel:#selector(WS_GetDetailsLoaded:) andHandler:self];`
//create class WSPContinuous and add these fns..
-(id)initWithRequestForThread:(NSMutableURLRequest*)urlRequest sel:(SEL)seletor andHandler:(NSObject*)handler {
if (self=[super init]) {
self.MainHandler = handler;
self.targetSelector = seletor;
self.urlReq = urlRequest;
[self performSelectorOnMainThread:#selector(startParse) withObject:nil waitUntilDone:NO];
}
return (id)urlReq;
}
-(void)startParse{
NSLog(#"URL CALLING %#",urlReq.URL);
con = [[NSURLConnection alloc] initWithRequest:urlReq delegate:self];
if (con) {
myWebData = [[NSMutableData data] retain];
NSLog(#"myWebData old....%#",myWebData);
}
else {
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
}
//-------------------------------connection-----------------
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[myWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[myWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self.MainHandler performSelectorOnMainThread:targetSelector withObject:nil waitUntilDone:NO];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *thexml = [[NSString alloc] initWithBytes:[myWebData mutableBytes] length:[myWebData length] encoding:NSUTF8StringEncoding];
NSLog(#"xmlDictionary %#",thexml);
[thexml release];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:myWebData error:&parseError];
[AlertHandler hideAlert];
[MainHandler performSelector:targetSelector withObject:xmlDictionary];
}
If you want to start, a better idea would be to do some reading on NSMutableURLRequest and related topics like NSURLConnection.
You get sample code everywhere. Just google it.
Google search -> objective c get and post
and First hit -> Tutorials for using HTTP POST and GET on the iPhone in Objective-C