I have a simple form interface set up that send username and password information to a server: (working)
NSString *postData = [NSString stringWithFormat:#"user=%#&pass=%#",[self urlEncodeValue:sysUsername],[self urlEncodeValue:password]];
NSLog(#"Post data -> %#", postData);
///
NSData* postVariables = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString* postLength = [NSString stringWithFormat:#"%d", [postVariables length]];
NSURL* postUrl = [NSURL URLWithString:#"http://localhost/~csmith/cocoa/test.php"];
[request setURL:postUrl];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postVariables];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSLog(#"Post data SENT & returned -> %#", returnData);
How do I handle connection errors such as no internet connection, firewall, etc.
Also, does this method use the system-wide proxy settings? Many of my users are behind a proxy.
Thanks a lot!
First, you shouldn't use synchronous requests, use asynchronous request instead and indicate activity using indeterminate progress indicators.
When using asynchronous requests, you have to set a delegate implement delegate methods, notably:
-connectionDidFinishLoading:
-connection:didFailWithError:
From the docs:
Unless a NSURLConnection receives a cancel message, the delegate will receive one and only one of connectionDidFinishLoading:, or connection:didFailWithError: message, but never both. In addition, once either of messages are sent, the delegate will receive no further messages for the given NSURLConnection.
As for the last question:
Also, does this method use the system-wide proxy settings?
Yes, NSURLConnection uses them automatically.
You should use asynchronous request to handle proxy and network errors. This is more efficient.
To add extra check you can add reach-ability test in your code before communications. you can find reach-ability test code here
Related
i'm developing an app for iPhone and I'm stuck in one call, I have to send data via POST, the django web programmer tells me the app has to receive
param_one = request.POST['param_one']
param_two = request.POST['param_two']
but I cannot make it to send any data...
I'm learning objective-c, so please, could you tell me how to do it with an example?
PS: all the other calls that doesn't send any data, or pass data through url (GET method) works fine, so I'm making the connection correctly
Here's the code I'm using:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"somename" forKey:#"user"];
NSString *jsonString = [dict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest * Â request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.com/custom/url/call/"]];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request addValue:csrf forHTTPHeaderField:#"X-CSRFToken"];
[request setHTTPBody:jsonData];
senddata = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You should probably add:
[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
Then the server will know that what you're sending is UTF-8 encoded JSON and it will be able to parse it appropriately. Otherwise it just gets a formless blob of data.
Unless it's for debugging purposes, it's very odd that you put the JSON string into both the header and the body.
I am building a JSON post in objective-c and sending it to an ASP.NET MVC controller.
I am building the NSMutableURLRequest as follows:
request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString* jsonRequest = [NSString stringWithFormat: #"{\"collection\":\"images\",\"id\":\"%#\",\"objectjson\":%#}",response.id,response.json];
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];
I then send the request as follows:
NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:backgroundQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{ ... completion code goes here
This works well most of the time. However, for very large JSON strings I occasionally get a web service error where the web service reports that it is encountering an End of File marker within the JSON. It appears that the JSON is being truncated.
I am sending the JSON to an ASP.NET MVC controller.
Does anyone have any words of wisdom on what might be happening? Are there any ASP.NET web configuration settings that perhaps I need to adjust to prevent this issue occurring.
One thing I don't understand is why it is such an intermittent problem.
This seems to be a result of bytes being lost over 3G or EDGE connection. The best idea I can come up with is to detect on the server that the content length header is larger than the request POST body and to return a status code that tells the client to try again. The client could pass a retry count on the url and the server could read it and if it's a certain value, the server would return an error code indicating that a retry should not be attempted. Ugly I know but I can't think of a better way. This is what I am going to do for my photo uploading app.
Good luck!
the problem is in the conversion to NSData
try this
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
The goal is to do a simple username/password authentication by querying a database. Until the connection is working decently my php destination file simply has following code:
echo "Posted: " . $_POST['email'];
The code to do this synchronously is this:
NSString *post = [[NSString alloc] initWithFormat:#"email=%#&password=%#", self.email.text, ..]; // .. simplified keychainItem
NSData *postEncoded = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postEncoded length]];
NSURL *url = [NSURL URLWithString:#"http://eng.studev.groept.be/web2.0/a11_web02/improver/app/testPost"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postEncoded];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *encodedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:encodedData encoding:NSUTF8StringEncoding];
NSLog(#"Data? %#",data);
The correct value is shown as an echo. But when trying to do this asynchronously, I get following php error: "Undefined index: email".
I try to start the asynchronous request with this line:
[[NSURLConnection connectionWithRequest:request delegate:self] start];
Then, I have the delegate method connection:didReceiveResponse, but there I cannot seem to get the data out... Or do I need another delegate method? Also, how 'safe' is it to check the result of your query by using just an echo (do I need/want a stream maybe?) ??
Tia
EDIT
Problem related to the server, not to objective-C code. Asked a new question to reach the correct audience: $_POST remaining empty
#ott is on the right track, I'll try to clarify.
You don't need start as he says. It's benign as the connection will start automatically.
initWithRequest:delegate and connectionWithRequest:delegate: are equivalent except for the retain state of the new connection object.
The real problem is b/c you are using connectionWithRequest:delegate the returned connection is autoreleased at the end of the run loop and you are not retaining it in a property. Therefore, the connection never starts.
The solution is to add a property #property (nonatomic, retain) NSURLConnection *connection to your class and set this property to the connection returned from connection:withRequest:
You then release the connection in the completion methods connection:didFinishLoading and connection:didFailWithError:.
The start is wrong here. Simply use
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
with NSURLConnection *connection; defined. See the class reference for connectionWithRequest. start is to be used with initWithRequest:delegate:.
I'm trying to create a synchronous REST request to an API. The API uses HTTP Basic authentication, so in addition to sending an Accept: application/json header, I need to specify the Authorization header as well with my Base64-encoded username and password pair. When I use just one header the request executes just fine (either successfully authenticating me, or specifying my content format), but when I use both headers, it seems to ignore the Authorization line and returns "HTTP Basic access denied" (presumably a 401).
So I can't for the life of me figure out whats wrong. I'm 100% sure my credentials are valid, because executing the request via REST client works just fine. I'm pretty new to Objective-C so I think perhaps there could be some kind of design pattern I'm not following. Is it valid to call setValue:forKey on an NSMutableDictionary multiple times like that? I also tried using setValue:forHTTPHeader on the request object with the same results.
Here's the code:
NSURL *url = [NSURL URLWithString:#"http://foo.com/api/v1/bar"];
NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *headers = [NSMutableDictionary dictionary];
NSURLResponse *urlResponse;
NSError *error;
[headers setValue:#"application/json" forKey:#"Accept"];
[headers setValue:#"Basic ..." forKey:#"Authorization"];
[request setAllHTTPHeaderFields:headers];
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding];
NSLog(#"%#",responseString);
The answer is to use:
[request addValue:#"Basic ..." forHTTPHeaderField:#"Authorization"];
Which adds another header into the request instance.
I've got a problem with my objective c code. I have a API-key protected WCF API that I built that takes POST requests and writes them to a Java servlet with C#. Anyway, this works great when testing with Fiddler, not so good from objective C. When I try to run the POST from my objective C, it "acts" like the NSURLMutableRequest is looking for a GET, in that the response only returns some default code I have written in for the GET method. Does anybody know why this is, and, moreover, what I can do to fix it? Here is the code that I use (quite successfully) to make other POST requests in with objective C.
is the problem the fact that I specify the API key in the URL for the NSMutableRequest? That's the only thing I can figure.
Here is the code:
NSString* theMessage = [NSString stringWithFormat:#"<MyRequestObject xmlns='http://schemas.datacontract.org/2004/07/MyService'></MyRequestObject>"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:POST_API_URL]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:240.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody:[theMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [theMessage length]];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
NSURLResponse* response;
NSError *error;
NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
I ended up using ASIHTTPRequest to run the POST request to the WCF REST service, and now everything seems to be running smoothly. This means that there's probably some sort of URL Encoding mechanism for the API key that's going on behind the scenes that was poorly documented for NSMutableURLRequest, who knows. The good thing is, I've got the issue fixed. Here is the code I used:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:POST_API_URL]];
[request appendPostData:[[NSString stringWithFormat:#"<MyRequest xmlns='http://schemas.datacontract.org/2004/07/MyService'>all of my request params in here</MyRequest>"] dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Content-Type" value:#"text/xml"];
[request startSynchronous];
Did you try setting the Content-Length header? WCF/IIS might be ignoring the body if it doesn't have its length defined in as a header.