This is how I am using the NSUrlConnection
- (void) serverHttpRequest:(NSString*)data
forUrl:(NSString*)Url
withTag:(NSString*)tag
httpType:(NSString *)type
forThisTime:(int)tryTime
withTimeOutInterval:(float)interval
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#", Url]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:interval];
[theRequest setHTTPMethod:type];
[theRequest setValue:#"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString *postData = data;
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
self.theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
[self.theConnection start];
}
But it fails to hit the server almost 50% time when called repeatedly. Why this is happening. The call frequency is per second.
The url is not same for all requests and the client is required to fetch data from multiple servlets on java server with Http POST request. May be something wrong configured on server side.
Possibly the problem is not on client side because when i Ran the same code on two different devices they both received error response at the same time. Also the devices are connected to internet via a proxy server. The error code is HTTP 503 . I know this error is shown when the server is overloaded or refused to respond, but it was working fine as it was receiving requests from other clients. I have implemented basic JAVA servlets and connecting it to MySql database using JDBC driver. If anyone could tell me how what configuration changes should i do on the server or client. THankyou
The only way I know of to determine why a server is sending back a 503 response is to check in the server's logs and see what went wrong. Either that or check the proxy server's logs.
Related
I've used NSMutableURLRequest for a long time to connect to my server.
In order to avoid double roadtrips, i set the usr/pwd right away in the header, like this:
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:HTTP_REQUEST_TIMEOUT];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", inUsr, inPwd];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [[authStr dataUsingEncoding:NSISOLatin1StringEncoding] base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
This has worked fine, the "willSendRequestForAuthenticationChallenge" is never called unless there is some error, so that method has always looked like:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSDictionary *errorInfo = ((NSHTTPURLResponse *) challenge.failureResponse).allHeaderFields;
NSError *error; = [NSError errorWithDomain:#"httprequesthandler" code:WRONG_CREDENTIALS userInfo:errorInfo];
[delegate finishedWithErrors:error];
Now however, i'm using the same URL's as always, only "https" instead of "http", and suddenly this method is called every time.
I want my request to work as per normal, i.e. populate basic header and only one request to the server.
I'm not sure what i'm missing, so pointers would be much appreciated!
Using https as your scheme (or protocol) requests the connection be made securely, both by encrypting the data that is transferred as well as offering some information to you about the authenticity of the server you are connecting to.
The delegate method being invoked here (connection:willSendRequestForAuthenticationChallenge:), is not related to you authenticating yourself with the server, but the server authenticating itself with you. If you dig into the challenge object (NSURLAuthenticationChallenge), you can find the credentials the server is offering to let you know that it is the server you were actually trying to connect to, instead of an impostor.
Normally you don't need to use this method unless you want to validate the server in a way that goes beyond what the OS is doing for already.
I am currently trying to make a REST call from an iOS device. My code is below
NSString *restCallString = [NSString stringWithFormat:#"MyURL"];
NSURL *url = [NSURL URLWithString:restCallString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"GET"];
[request addValue:Value1 forHTTPHeaderField:#"Header1"];
[request addValue:Value2 forHTTPHeaderField:#"Header2"];
[request setURL:[NSURL URLWithString:restCallString]];
#try{
_currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#catch(NSError *e){
NSLog(#"%#", e.description);
}
Whenever this is called, I get the following error: Authentication credentials were not provided. However, what confuses me is that if I send an identical GET request via a HTTP web console, it works perfectly. In other words, using the same URL and the same 2 header-value pairs, I get a valid response on a web console, and see no authentication errors. What could be causing this?
You are setting the HTTP headers. This won't work, because the HTTP header is not contained in $_GET or $_POST because they're are not content, but description of the content expected.
Try this instead:
NSURL *url = [NSURL URLWithString:[restCallString stringByAppendingFormat:#"?Header1=%#&Header2=%#", Value1, Value2]];
Of cause you have to be aware that the URL is RFC 1738 compliant.
if I send an identical GET request via a HTTP web console, it works perfectly
I suspect your web console is leveraging SessionAuthentication — i.e. If you're already logged in to your site in your browser the API will authenticate you based on your session cookie.
Django Rest Framework provides various authentication methods and there are third-party options too. The simplest to get going is probably the provided Token Auth method.
Make sure this is enabled. Create a token in the admin (or via the provided view) and make sure you've set the Authorization header. It needs to look like this:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
So your Objective-C will go something like:
[request addValue:[NSString stringWithFormat:#"Token %#", yourToken]
forHTTPHeaderField:#"Authorization"];
Hopefully that gets you started.
I'm trying to download a file from a cloud via a GET HTTP request, and in my REST Client (Postman for Chrome) I get the results as expected, but when I pass the request in iOS, I get a NULL response. What could be the problem?
In my REST Client, I pass the URL as http://myserver.com/api/download.json?filepath=/&fileid=document:1pLNAbof_dbXGn43GtMNafABMAr_peTToh6wEkXlab7U&filename=My Info.doc with a header field for a authorization key, and it works perfectly fine.
While in iOS, if I do such a thing:
[request setURL:[NSURL URLWithString:URLString]]; // I tried even to hardcode the
// URLString to be one of the
// working URLs from the Postman
// Client, doesn't work as well.
[request setHTTPMethod:#"GET"];
NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponseList
error:&requestErrorList];
response is null, and I get a status code 500.
Anyone know how to make this work? Thanks.
it looks like your URL has a space in it, you'll need to escape that before sending the string to NSURL.
it would also be helpful to know what the full error from your server is if this doesn't work. what does requestErrorList contain?
but if the only problem is the non-escaped characters something like this should work.
NSString *encodedString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[request setURL:[NSURL URLWithString:encodedString];
An HTTP status code 500 occurs when the webservice is not able to handle your request. An internal error occured.
Try to add some more details to your request.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
I need some tutorial, how to use HTTP POST (or GET) request from my iOS app. I want to send one string to my server and than write it to database. I've found this piece of code:
NSString *post = #"key1=val1";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
I add it to UIAction button, but it don't send anything to my server. On my server, I have a PHP script that takes that "key1" from post and than it write it to db.
<?
$postr = $_POST["key1"];
$con0 = mysql_connect("server","db","pass");
mysql_select_db("table", $con0);
mysql_set_charset('utf8',$con0);
mysql_query("INSERT INTO tok (token) VALUES ('$postr')");
mysql_close();
?>
Can anybody tell me what I am doing wrong?
Look at AFnetworking and work through their api. Sending a post request using the api is very fast, and is what most apps use for web connectivity.
Also please dont be discouraged by sarcastic comments. You should tag iOS projects as iOS and not xcode (unless you actually need help with the actual program xcode). But I don't think it's productive to harrass everyone that comes in and makes this mistake. A more tactful way would be a personal message as opposed to a public retort
https://github.com/AFNetworking/AFNetworking
AFNetworking is a very powerful library that can help you to reduce the effort on create your HTTP requests, you can find several examples on how to use this library on its github page.
You may find this answer useful for your needs: AFNetworking Post Request
I am trying to send a suggestion from my app to a php file on my web server, I have tested the php script in my browser which sends an email to the user and stores the suggestion in my database, which all works fine.. And when running the following script I get a successful connection via IOS however i do not receive the results in my database..
NSString *post = [NSString stringWithFormat:#"http://blahblah.com/suggest.php?s=%#&n=%#&e=%#", suggestion, name, email];
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:post]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
NSLog(#"Connection establisted successfully");
} else {
NSLog(#"Connection failed.");
}
I have checked all the strings and encoded all spaces with %20 etc.. Can anyone see any glaringly obvious reason why my script won't work?
What is the easiest way to make a HTTP request from my app without opening safari?
You problem is that you're creating the connection, but are not sending the actual "connect" request. Instead of
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
try using this piece of code:
NSURLResponse* response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]
This is quick and dirty solution, but keep in mind that while this connection is in progress, your UI thread will appear to be frozen. The way around it is to use asynchronous connection method, which is a bit more complicated than the above. Search web for NSURLConnection send asynchronous request - the answer is there.