NSURLConnection parse issue - ios7

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SPACEREQUESTFINAL_URL] cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"mymac", #"qerty!98"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedString]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:120];
[request setAllHTTPHeaderFields:jsonDictionary];
NSHTTPURLResponse* urlResponse=nil;
NSError *error=nil;
NSData *serverResponse = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSLog(#"ServerResponse %#",serverResponse);
if (error==nil)
{
[NSURLConnection connectionWithRequest:request delegate:self];
NSString *str1=[[NSString alloc]initWithData:serverResponse encoding:NSUTF8StringEncoding];
NSLog(#"SSTR %#",str1);
NSMutableDictionary *JsonDict=[NSJSONSerialization JSONObjectWithData:serverResponse options:NSJSONReadingAllowFragments error:&error];
}
Data is not parsing
ServerResponse is coming null -- request is not responding to NSURLConnection may be
Please suggest how to resolve it.
Thank you

NSMutableDictionary *datadict=[NSMutableDictionary dictionary];
[datadict setObject:[NSString stringWithFormat:#"%#", mymac] forKey:#"yourkeytoidentify"];
[datadict setObject:[NSString stringWithFormat:#"%#",qerty!98] forKey:#"yourkeytoidentify"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:datadict options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#" url "];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
NSError *error;
NSURLResponse *response;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * string1=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",string1);
}
}

Related

NSMutableURLRequest response null

I am trying to make a POST request with encrypted string using following code. In response I get null from server. I test with this https://www.hurl.it using same value and get 200. Can't figure out where is the problem.
To encode string I have use
NSUTF8StringEncoding
NSASCIIStringEncoding
NSNEXTSTEPStringEncoding
forD = #"AAAAAAAAAMCYdiQv+wcAsBAAAAAAAAAAaQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMQswCQYDVQQGEwJVUzETMBEGA1UECBMKTkVXIEpFUlNFWTEZMBcGA1UEChMQVkVSSVpPTiBXSVJFTEVTUzENMAsGA1UECxMETUlQUzEbMBkAAAAAAAAAwAAAAAAAAADACABUSUNTLTAxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUfCQv+wcA8L4GJC/7BwAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1ZwkL/sHAFCDeyQv+wcQAA==";
NSData* requestData = [forD dataUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:baseURL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"1" forHTTPHeaderField:#"Appversion"];
[request setValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setValue:#"gzip,deflate" forHTTPHeaderField:#"Accept-Encoding"];
[request setHTTPBody: requestData];
NSLog(#"%#", [request allHTTPHeaderFields]);
NSLog(#"%#", [request HTTPBody]);
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"\n\n === RESPONSE SERVER ==== \n\n %#",[NSJSONSerialization JSONObjectWithData:receivedData options:0 error:nil]);

Post XML data with ASIFormDataRequest error

NSURL *postUrl =[[NSURL alloc] initWithString:mainString];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:postUrl];
[request setResponseEncoding:NSUTF8StringEncoding];
NSString *msgLength = [NSString stringWithFormat:#"%d", [xmlString length]];
[request addRequestHeader:#"Content-Length" value:msgLength];
NSString *contentType = [NSString stringWithFormat:#"application/xml"];
[request addRequestHeader:#"Content-Type" value:contentType];
// [request addRequestHeader:#"Content-Type" value:#"application/json"];//Test For JSON is good
[request appendPostData:theData];
[request buildPostBody];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request startAsynchronous];
[request setTimeOutSeconds:20];// 测试连接的时间,默认10s
[postUrl release];
I get Nothing from the following code, which also does not produce an error.
(void)requestFinished:(ASIHTTPRequest *)request{
NSData *theData = [request responseData];
NSString *ret = [request responseString];
NSLog(#"ret--------------%#",ret);
}
When I use JSON, I get the result.

Sending JSON through POST not working - Objective C

I am sending a JSON string to our server using the POST method. What should happen is that it should return a response showing "Array(JSON String) Array(JSON String)". The response contains two arrays: The first array is populated if I used the POST method, while the second array is populated if I use the GET method. I tried sending the JSON through GET method and indeed, the second array was populated. However, when I tried to send JSON through POST method, both arrays are returned empty.
Here is the code I used:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:sqlArray options:NSJSONWritingPrettyPrinted error:&error];
NSURL *url = [NSURL URLWithString:#"http://myurl/xmlrpc/imwebsrvcjson.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
NSData *result =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if (error == nil){
NSLog(#"The Result string: %#", returnString);
}
Can you tell me what is wrong with my code?
Here's what I do (please note that the JSON going to my server needs to be a dictionary with one value (another dictionary) for key = question..i.e. {:question => { dictionary } } ):
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
receivedData = [[NSMutableData data] retain];
}
The receivedData is then handled by:
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *question = [jsonDict objectForKey:#"question"];
This isn't 100% clear and will take some re-reading, but everything should be here to get you started. And from what I can tell, this is asynchronous. My UI is not locked up while these calls are made. Hope that helps.

passing JSON data with hebrew values problems (UTF8?)

i have this method -
NSArray *objects = [NSArray arrayWithObjects:appDelegate.UserID,itemName.text,#"1",#"1",itemDegem.text,itemDescription.text, nil];
NSArray *keys = [NSArray arrayWithObjects:#"userId",#"itemName",#"itemCategoryId",#"regionId",#"degemName",#"itemDescription", nil];
NSDictionary *registerDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonRequest = [registerDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://www.somedomain.com/method"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
self.responseData = [NSMutableData data];
}
but when i send strings in my objects that not in english im getting error from the server.
now, i know its a UTF8 problem, but i did set it to be UTF8. can someone please help me figure it out ?
I think the error is strlen([jsonRequest UTF8String]) is not equal to [jsonRequest length].
Use NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; to convert a NSString into NSData using UTF8 encoding.

Objective-C &JSONKit POST issue

I'm trying to post to a rails backend from Objective-C and JSONKit and am having difficulty getting my results published. I keep getting back a null recordset from my server.
[dictionary setValue:(#"bar") forKey:#"foo"];
NSString *JSON = [dictionary JSONString];
NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: myUrl];
NSString *postLength = [NSString stringWithFormat:#"%d", [theData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSError *error = NULL;
NSURLResponse *response = nil;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json-rpc" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:theData];
NSData *result = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(resultString);
Is there something I'm missing? the JSON seems to be serializing correctly
{"foo":"bar"}
Any help would be greatly appreciated.
Thanks!
Just changed the setValue from json-rpc to json and it worked like a champ.
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
**[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];**
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setHTTPBody:theData];