Post XML data with ASIFormDataRequest error - objective-c

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.

Related

NSURLConnection parse issue

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);
}
}

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.

NSURLConnection freeze

I'm trying to send JSON post using NSURLConnection:
NSURL *url = [NSURL URLWithString:urlStr];
NSString *jsonPostBody = [NSString stringWithFormat:#"{\"user\":""\"%#\""",\"pass\":""\"%#\""",\"listades\":\"\"}",
[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"JSNON BODY:%#", jsonPostBody);
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
[request setTimeoutInterval:2.0];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:#"%d", [postData length]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
App execution gets freeze when it reaches connection command, despite timeout.
I'm stucked in this issue and I can not find a solution.
Many thanks
-(void) jsonRESTWebServiceMethod:(NSString*)method WithParameter:(NSMutableDictionary*)params{
self.iResponseType = JSONTYPE;
NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:method,#"name",params,#"body",nil,nil];
NSData *data = [[CJSONSerializer serializer] serializeObject:bodyDict error:nil];
NSString *strRequest = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
strRequest = [NSString stringWithFormat:#"json=%#",strRequest];
NSData *body = [strRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString *strURL = [NSString stringWithString:WebServiceURL];
NSString* escapedUrlString = [strURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:escapedUrlString]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
NSString *msgLength = [NSString stringWithFormat:#"%d",strRequest.length];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField: #"Content-Type"];
[request addValue:msgLength forHTTPHeaderField:#"Content-Length"];
if (mydata) {
[mydata release];
mydata = nil;
}
conections = [[NSURLConnection alloc] initWithRequest:request delegate:self];
mydata = [[NSMutableData alloc] init];
}
It's freezing your app because you have passed YES into startImmediately. This will freeze the app until request is finished.
You need to use something like connectionWithRequest:delegate: - this will run the request in the background and tell you when it's done.
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];

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];