Twitter api request using simple NSMutableURLRequest - objective-c

I am trying to get a user latest twits , with a simple request but getting a code error 400 .
What am i missing with my request body ?
NSString *consumerKey = #"api key";
NSString *consumerSecret = #"api secret";
NSString *consumerKeyRFC1738 = [consumerKey stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSString *consumerSecretRFC1738 = [consumerSecret stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSString *concatKeySecret = [[consumerKeyRFC1738 stringByAppendingString:#":"] stringByAppendingString:consumerSecretRFC1738];
NSLog(#"-%#",concatKeySecret);
NSString *concatKeySecretBase64 = [[concatKeySecret dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2"]];
[request setHTTPMethod:#"POST"];
[request setValue:[#"Basic" stringByAppendingString:concatKeySecretBase64] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
NSString *str = #"grant_type=client_credentials";
NSData *httpBody = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:httpBody];
//NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
if ([response respondsToSelector:#selector(allHeaderFields)])
{
NSDictionary *dictionary = [response allHeaderFields];
NSLog(#"%#",dictionary);
NSLog(#"%#",response);
}
The respond giving me this :
<NSHTTPURLResponse: 0x10cc21ba0> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2 } { status code: 400, headers {
"Content-Encoding" = gzip;
"Content-Length" = 86;
"Content-Type" = "application/json; charset=utf-8";
.....
....

If it suits your needs, I'd recommend you using SLRequest. Please note that this framework will ask for permission to use the user's account.
NSURL *showUserURL = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json"];
NSDictionary *parameters = #{ #"screen_name": #"thestrayhotdog" };
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:showUserURL
parameters:parameters];
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray * accounts = [accountStore accountsWithAccountType:accountType];
if ([accounts count]) {
ACAccount *twitterAccount = [accounts firstObject];
request.account = twitterAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *connectionError) {
NSLog(#"%#",[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding]);
NSLog(#"Status code: %ld",(long)[urlResponse statusCode]);
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
// Handle error
}
// success;
}];
}
}
}];

Related

Parse xml(from web service) to NSDictionary in objective c

I do synchronous post request and get xml. Now I need parse and save it in NSDictionary. I tried many solutions from the web. But nothing worked for me. Here's my code:
//Response data object
NSData *returnData = [[NSData alloc]init];
NSString *param = #"{params}";
NSString *postString = [NSString stringWithFormat:#"request=%#",param];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:response];
if (debug && response) {
NSLog(#"Response >>>> %#", xmlDoc);
}
I used this xml reader. Here is result which I get in nslog:
2016-11-28 18:04:26.970 SyncPostReq[8667:305923] Response >>>> (null)
NSURL *url = [NSURL URLWithString:#"url"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSError *parseError;
NSDictionary* xmlDict1 = [XMLReader dictionaryForXMLData:data error:&parseError];
NSDictionary *dictData = [xmlDict1 objectForKey:#"event_listing"];
arrData = [dictData objectForKey:#"event"];
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
[defaults setObject:arrData
forKey:#"Keyupevent"];
[defaults setBool:YES forKey:#"KeyalldataLoad"];
[defaults synchronize];
uparrData =[[defaults objectForKey:#"Keyupevent"] mutableCopy];
[arrStoreAllEventsData addObjectsFromArray:uparrData];
[self.tblView reloadData];
[self loadPastEventdatafromxml];
}] resume];

How to check JSON post return value

I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link

POST Method With Multiple JSON Objects(Objective C)

Hello everyone I m trying to send two json objects in one request.
Here is what I did so far:
NSDictionary *credentials = [request getCredentials];
NSURL *url = [NSURL URLWithString:#"https://myurl.com"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
req.HTTPMethod = #"POST";
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSData *o = [NSJSONSerialization dataWithJSONObject:output
options:NSJSONWritingPrettyPrinted error:&error];
NSData *c = [NSJSONSerialization dataWithJSONObject:credentials
options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:o encoding:NSUTF8StringEncoding];
NSLog(#"DATA: %#",myString);
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req
fromData:c completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(#"RESPONSE %#", response);
}];
[uploadTask resume];
}
In this code I send only "NSData *c" but also I want to send "NSData *o" in the same request. Is it possible, I need your helps. Thanks.
you can combine dictonaries into one using below code then post to server.
#property (nonatomic, strong) NSMutableDictionary *configuration;
...
-(NSMutableDictionary*) configuration{
if (!_configuration) {
NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"installation" ofType:#"plist"]];
NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:#"/path/to"] pathForResource:#"something/data" ofType:#"plist"]];
[_configuration addEntriesFromDictionary: core_config];
[_configuration addEntriesFromDictionary: app_config];
NSLog(#"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count], (unsigned long)[core_config count], (unsigned long)[app_config count]);
// merged: 0, core: 4, app: 5
}
return _configuration;
}

Sending params with POST Req in JSON with AFNetworking

I have a small problem with AFNetworking.
I'm not able to send the parameters and the data to my server (php-Skript)
The data (from NSDictionary) have to be JSON.
Ignore the senseless code parts please.
I'm receiving Errors like:
NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
or Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
NSDictionary *parameter = [[NSDictionary alloc]init];
parameter = #{#"device-id": #"iOSDeveloper1234567432",#"system": #1,#"token": #"iOS-TestToken",#"mail_enabled": #"false",#"mail": #"NULL", #"movies": #[#"matrix", #"matrix2", #"matrix3"]};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *stringkey;
stringkey = (#"k=");
stringkey = [stringkey stringByAppendingString:APIKEY];
NSString *strings;
NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
myString = [myString stringByAppendingString:(#"&k=")];
myString = [myString stringByAppendingString:APIKEY];
NSLog(#"%#",myString);
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = [myString dataUsingEncoding:NSSymbolStringEncoding];
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:&error];
NSLog(#"%#",error.localizedDescription);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL parameters:myString progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Simple objective-c GET request

Most of the information here refers to the abandoned ASIHTTPREQUEST project so forgive me for asking again.
Effectively, I need to swipe a magnetic strip and send the track 2 data to a webservice that returns "enrolled" or "notenrolled" (depending on the status of the card...)
So my data comes in simply as
NSData *data = [notification object];
And then I need to pass this to a url to the order of
http://example.com/CardSwipe.cfc?method=isenrolled&track2=data
And then just receive a response string...
I've searched a ton and there seems to be some conflicting answers as to whether this should be accomplished simply with AFNetworking, RESTkit, or with the native NSURL/NSMutableURLRequest protocols.
The options for performing HTTP requests in Objective-C can be a little intimidating. One solution that has worked well for me is to use NSMutableURLRequest. An example (using ARC, so YMMV) is:
- (NSString *) getDataFrom:(NSString *)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:url]];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(#"Error getting %#, HTTP status code %i", url, [responseCode statusCode]);
return nil;
}
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
Update:
Your question's title, and tagging say POST, but your example URL would indicate a GET request. In the case of a GET request, the above example is sufficient. For a POST, you'd change it up as follows:
- (NSString *) getDataFrom:(NSString *)url withBody:(NSData *)body{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
[request setValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
[request setURL:[NSURL URLWithString:url]];
/* the same as above from here out */
}
Update for iOS 9:
So, [NSURLConnection sendSynchronousRequest] is deprecated starting from iOS 9. Here's how to do a GET request using NSURLSession starting from iOS 9
GET Request
// making a GET request to /init
NSString *targetUrl = [NSString stringWithFormat:#"%#/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data received: %#", myString);
}] resume];
POST Request
// making a POST request to /init
NSString *targetUrl = [NSString stringWithFormat:#"%#/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Make an NSDictionary that would be converted to an NSData object sent over as JSON with the request body
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"basic_attribution", #"scenario_type",
nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data received: %#", responseStr);
}] resume];
Tested 100% working
Only for Objective C
-(void)fetchData
{
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:#"https://test.orgorg.net/ios/getStory.php?"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = #"";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//JSON Parsing....
NSString *message = results[#"Message"];
BOOL status = results[#"Status"];
if (status){
// Here you go for data....
}else{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:#"App"
message:message
preferredStyle:UIAlertControllerStyleAlert]; // 1
UIAlertAction *firstAction = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"You pressed button one");
}]; // 2
[alert addAction:firstAction]; // 4
[self presentViewController:alert animated:YES completion:nil];
}
}];
// Fire the request
[dataTask resume];
}
For Objective c :
-(void)loadData:(NSString*)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://jsonplaceholder.typicode.com/posts"]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableArray *jsonArray = (NSMutableArray *)[NSJSONSerialization JSONObjectWithData:data options:NSASCIIStringEncoding error:&error];
if([self.delegate respondsToSelector:#selector(loadingData:)]){
[self.delegate loadingData:jsonArray];
}
}] resume];
}
Swift 5.5:
// MARK: - Posts
func getPosts(endPath : String, completion: #escaping ([Post]) -> ()) {
let urlPath = Constants.Network.BASE_URL + endPath
guard let url = URL(string: urlPath) else {
print("Invalid URL")
return
}
var request = URLRequest(url: url)
request.httpMethod = Constants.Network.HTTPS_METHOD
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode([Post].self, from: data) {
DispatchQueue.main.async {
completion(decodedResponse)
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
**Simply Call and get your JSON Data.**
-(void)getJSONData
{
NSURL *url = [NSURL URLWithString:#"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSError *erro = nil;
if (data!=nil) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];
if (json.count > 0) {
for(int i = 0; i<10 ; i++){
[arr addObject:[[[json[#"feed"][#"entry"] objectAtIndex:i]valueForKeyPath:#"im:image"] objectAtIndex:0][#"label"]];
}
}
}
dispatch_sync(dispatch_get_main_queue(),^{
[table reloadData];
});
}];
[data resume];
}