I'm writing some with server API. I'm using RestKit but this question I wrote without. I don't understand why console request is working and my is not. Please help me with this.
-(void)uploadFile {
NSString *URLPath = [NSString stringWithFormat:#"https://api.interlabs.pro/v1/texts/23041/content"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URLPath]];
[request setHTTPMethod:#"PUT"];
[request addValue: #"Bearer ewogICAgInR5cCI6ICJKV1QiLAogICAgImFsZyI6ICJIUzI1NiIKfQ.ewogICAgImlzcyI6ICJhcGkuaW50ZXJsYWJzLnBybyIsCiAgICAiaWF0IjogMTQ2MzY3ODg2NCwKICAgICJleHAiOiAxNDYzNjgyNDY0LAogICAgInN1YiI6IDgzCn0.SuvGXfsDDzpA5-qJtRUZi7uw98IqA8_axfTGcMVjZdw" forHTTPHeaderField: #"Authorization"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(resSrt);
}
And it's still doesn't not work, but console work perfectly
But enter link description here
update token link
The code works fine and result is that token is expired.
But you should not use deprecated methods like "NSURLConnection sendSynchronousRequest", then you should check error, when handling results from internet it is utf8 most of the time and not ascii. Then when logging strings use NSLog(#"%#", theString) to avoid problems if the content of theString contains formating specifiers.
Related
So, I have to methods to approach a web service:
A GET:
- (NSDictionary *)getDataFromURL:(NSString*)url {
NSString * serverAddress =[NSString stringWithFormat:url,mySchoolURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&urlResponse
error:&requestError];
NSError* error = nil;
NSDictionary *output = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
return output;
}
and a POST:
-(NSData*)postData:(NSDictionary*)requestData toUrl:(NSString*)destination {
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:destination,mySchoolURL]]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postdata];
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return nil;
}
Somehow, the HTTP header of the POST method does include the cookie's SessionID, while the GET one doesn't.
I have to admit that I don't fully understand the innards of cookies and the like, but several sources on the web claim that I should't worry about the cookies at all, since they are taken care of automatically.
Anyway, the web service I'm talking to expects a Session ID in both POST and GET situations, so now I'm forced to start understanding what's going on.
Could any of you help me out here?
The concrete question is: how to I pass a Session_ID to a URL using a GET method?
Thanks ahead
Okay so one way to do this is by simply adding the cookies to the HTTP headers. When doing this the correctness of the URL is key. If the protocol is wrong, some cookies may not be included. You will need to get all available cookies, and then create a dictionary for the headers with he available cookies. Then you simply add those headers to your request by calling setAllHTTPHeaderFields:. I placed a quick example of how to do this below, however you can learn more about how cookies work at the Apple Documentation Class Reference
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers];
I really hope this helps you out. I would recommend reading the Apples Documentation to help you out as much as possible. I wish you the best of luck!
I came to the last stage of development of my app and here is the bit that I've never done before.
My friend has developed and API for my app to send and receive data, using django rest framework.
I need to authenticate my app to connect to it, send some data and receive data.
What I have found so far is:
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/my/path/to/api/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"myUsername", #"myPassword"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", authData];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//------------------------------------------------------------------------------------------------------------------------------------//
//EDIT: Added this based on answer form #Quver.
NSURLResponse *response1;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&responseError];
if (result.length > 0 && responseError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:result
options:0
error:NULL];
NSLog(#"Got response form server: %#", greeting);
}
This equals output like:
<0a0a3c68 746d6c3e 0a0a2020 20203c68 6561643e 0a202020 20202020 200a2020 20202020 20200a20 20202020 + ~50 lines of similar stuff. Hope this helps.
//-----------------------------------------------------------------------------------------------------------------------------------------//
I guess this is the way to create request. What should I do next? And how do I know that I have connected?
Then, if I have connected, how do I get data form there? (I have a url that gives me json as output - this is what I want to get). Assume the url to be http://localhost:8080/url/that/gives/json/.
Thank you for any help. Hope this is enough information for the question. I will add anything else required.
NSURLResponse *response;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
Add this to get response. You already prepared request, now it's time to send it with NSURLConnection. I you sync request insted of async, becouse of using GCD for whole metod request + sqlite update.
After a few days of searching I have found a way.
First, we need a token for authentication. I am generating it through terminal for now:
curl -X POST -d "grant_type=password&username=<your username>&password=<your password>" http://<client secret>:<client id>#url/to/token/page
Then, in your view controller where you want to connect:
//always put </> at the end of link
NSURL *aUrl = [NSURL URLWithString: #"http://where/you/trying/to/conect"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:#"<type> <your token>"] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
self.response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
This will return any json that the page supposed to return. This might not be the most secure way, but this is exactly what I need for now. I will look at more secure solutions like OAuth 2, later.
Hope this helps to someone.
Hi I'm new to iphone development, I'm currently working with a project where I have a screen, in which user should enter their details, like username and password. I googled and find out about NSURLConnection for GET/POST/DELETE. I can GET data by the below codes,
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://************/api/Users"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-
Type"];
NSURLResponse *response;
NSData *GETData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *ResultData = [[NSString alloc] initWithBytes:[GETData bytes] length:[GETData
length] encoding: NSASCIIStringEncoding];
NSLog(#"ResultData: %#", ResultData);
But for POST method, i doesn't get any ideas of , how it functions and how it store record to sql server database, can't understand whether it s storing data or not, i tried the following codes,
username = #"Aravind.k";
password = #"1234/";
email = #"sivaarwin#gmail.com";
NSString *post = [NSString stringWithFormat:#"FirstName=%#&LastName=%#&WorkEmailAddress=%#",
username, password, email];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://*********/api/Users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"request: %#", request);
NSLog(#"postData: %#", postData);
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];
NSLog(#"POSTReply: %#", POSTReply);
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes]
length:[POSTReply length]
encoding:NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
Same api url for both GET and POST, any suggestions regarding POST and DELETE will be grateful, Thanks in advance.And how we can get notified as the entered data is stored into the server.
First off: not checking for errors automatically leads to down votes ;)
Please edit your code with full error checks!
When using a MIME type application/x-www-form-urlencoded you need to properly encode the parameters.
I would suggest, to create a NSDictionary holding your parameters, e.g.:
NSDictionary* params = #{#"FirstName": firstName, #"LastName": lastName, #"password": password};
and then use the approach described in the following link to get an encoded parameter string suitable for using as a body data for a application/x-www-form-urlencoded message:
How to send multiple parameterts to PHP server in HTTP post
The link above implements a Category and a method dataFormURLEncoded for a NSDictionary which returns an encoded string in a NSData object:
NSData* postData = [params dataFormURLEncoded];
Note: The MIME type application/x-www-form-urlencoded does not have a charset parameter. It will be ignored by the server. You should set the header like below:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Otherwise, your code should work. I would strongly recommend to use the asynchronous version of the convenient method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
I'm trying to make a POST request using NSURLConnection. I use Charles to debug and Charles every time says that the method is GET. I've tried all different ways and can't get it to work. I am NOT using JSON.
-(void)getList
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *url = [NSURL URLWithString:#"http://example.com/api/getList"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *radius = #"15";
NSString *latitude = #"-117.820833";
NSString *longitude = #"34.001667";
NSString *parameters = [NSString stringWithFormat:#"longitude=%#&latitude=%#&radius=%#", longitude,latitude, radius];
NSLog(#"PARAMS = %#", parameters);
NSData *data = [parameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"RESULT = %#", responseString);
}
Does anybody know what am I doing wrong? When I access my web service it seems like I'm not posting anything. I'm getting empty response.
Please help with any ideas. I pretty much have to make a simple POST request. Maybe someone can help me debug this better.
If the server is redirecting your request for some reason (perhaps authentication) then the POST information can get lost.
I am trying to edit the wikitext of a page using a textView and save it on the server using mediawiki API as follows:
- (void)saveAction{
NSString *savedString = textView.text;
NSString *baseurl=[[NSUserDefaults standardUserDefaults] stringForKey:#"url_preference"];
NSString *page=[[baseurl stringByAppendingString:#"/api.php?**action=edit&title=Testedit&text=savedString&token=**"] stringByAppendingString:[MySingleton sharedSingleton].token];
NSData *data=[savedString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%d",[data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:page]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSError *error=nil;
NSURLResponse *response=nil;
NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *HTMLString2 = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"%#", HTMLString2);
}
but I am getting an error : internal_api_error_MWException,
Exception Caught: Detected bug in an extension! Hook iaifAPIEditBeforeSave has invalid call signature; Parameter 1 to iaifAPIEditBeforeSave() expected to be a reference.
Searched about the error on google but I didn't find anything. Please suggest something.
That wiki appears to have an outdated Data Import Extension. Update/uninstall as required. A quick hack that should fix this particular error would be to replace function iaifAPIEditBeforeSave(&$editPage, $text, &$resultArr) with function iaifAPIEditBeforeSave($editPage, $text, &$resultArr) in extensions/DataImport/IAI/includes/IAI_GlobalFunctions.php, however I don't know what else could be outdated/broken there.