I try to send a large string 30k with NSURLRequest via NSSession downloadTaskWithRequest but all datas are not sent ?!
-(NSURLRequest*) GetMySQLCommand
{
NSString *StringToSend = [NSString stringWithFormat: POST_SEND_SQL, _myHashIdstr, _mySQLType, _mySQLStringCommand, _mySQLProcReturn, _myStrId];
NSLog(#"-----> Post Data = %#", StringToSend);
NSData *postData = [StringToSend dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%llu", (unsigned long long)[postData length]];
NSLog(#"-----> Post Data to send = %#", postLength);
_myRequest = [[NSMutableURLRequest alloc] init];
[_myRequest setHTTPMethod:#"POST"];
[_myRequest setURL:[NSURL URLWithString:_myIpAdress0]];
[_myRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[_myRequest setValue:#"text/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[_myRequest setHTTPBody:postData];
return _myRequest;
}
Related
i'm trying to send an HTTP post request from my objective-c application to my server. i tried many different things, but i can't get the request to work with the content on request body. With the parameters on the url it work just fine, but i need to send a string with reserved characters.
This is my class responsible for the request:
#import "CLPUtilRequest.h"
static NSString *baseURL = #"http://localhost:8080/cl-mobile";
#implementation CLPUtilRequest
//Parameteres on the URL (working!!)
+ (NSData *) makeHttpRequest:(NSString *)url {
//Set info for webservice
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
NSURL *resquestUrl = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:resquestUrl];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/http" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//Call the webservice
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
return [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
}
//Parameteres on the bodt (not working!!)
+ (NSData *) makeHttpRequestContentOnBody:(NSString *)url withContent:(NSString *)content {
NSData *postData = [content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[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];
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
return data;
}
#end
And this is where i call the request.
NSString *contentString = #"chaveUsuarioEmpresa=";
contentString = [contentString stringByAppendingString:appDelegate.clinica.chave];
contentString = [contentString stringByAppendingString:#"&chaveAgendamento="];
contentString = [contentString stringByAppendingString:appDelegate.agendamento.chave];
contentString = [contentString stringByAppendingString:#"&anamnese="];
contentString = [contentString stringByAppendingString:self.texto.text];
NSData *dataResponse = [CLPUtilRequest makeHttpRequestContentOnBody:#"/agendamento/anamnese/save" withContent:contentString];
After calling the request, my errorReturned gives me the following (debugging): NSURLError * domain: #"NSURLErrorDomain" - code: -1002
I tried to do as described in this link (but didn`t make it): Sending an HTTP POST request on iOS
Thanks in advance!
according to Apple's Error Codes -1002 is the code for an unsupported url. and actually you are sending it to /agendamento/anamnese/save, as you don't prepend baseURL as you do in the other call
+ (NSData *) makeHttpRequest:(NSString *)url {
//Set info for webservice
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
NSURL *resquestUrl = [NSURL URLWithString:urlString];
while in makeHttpRequestContentOnBody:withContent: you use the unchanged passed in url string /agendamento/anamnese/save
Try
+ (NSData *) makeHttpRequestContentOnBody:(NSString *)url withContent:(NSString *)content
{
NSData *postData = [content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *urlString = baseURL;
urlString = [urlString stringByAppendingString:url];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *errorReturned = nil;
NSHTTPURLResponse *theResponse =[[NSHTTPURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
return data;
}
I'm trying to send the content of my textfields firstname and lastname with my button sendpost to my php server. Once I run my app and fill my textfields with some random text and press send, I receive an e-mail on my server but there is no content.
(void) sendAction{
NSError *error = nil;
NSString *postparams = [NSString stringWithFormat:#"info=%#_%#",firstname.text,lastname.text];
NSData * postdata = [postparams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postlength= [NSString stringWithFormat:#"%d",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://faketest.com/test/mail.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postdata];
NSData * rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *rawdatastring =[[NSString alloc]initWithData:rawdata encoding:NSUTF8StringEncoding];
NSLog(#"%#",rawdatastring);
}
I believe it may be because you're using a "Current-Type" header, instead of the usual "Content-Type" header. Try the following and see if it solves the problem:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
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.
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];
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];