AFNetworking building a URL for GET with parameters - ios

I have a few paramaters I want to pass to the URL when performing a GET
The method I use for building the URL is:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: baseURL];
NSString* url = #"http://pretendurl.com/something";
NSMutableURLRequest *request = [httpClient requestWithMethod: #"GET"
path: url
parameters: params];
Where params is an nsdictionary that has been populated.
This adds the parameters to the url file but it adds &format=json to the end of the URL.
I would like to know how to get it to build the URL without the last piece. I had a look through the AFNetworking source code but couldn't spot where it actually adds that bit.
Thanks in advance.

you could convert you dictionary params to query url using a function like this
-(NSString*) getQueryUrlFromDictionary:(NSDictionary*) dict usingUrlEncoder:(BOOL)makeUrlEncoded
{
if (dict == nil)
return #"";
NSMutableString* outputStr = [[NSMutableString alloc] initWithString:#""];
int px = 0;
for (NSString* key in dict) {
NSString* param = (NSString*) [dict objectForKey:key];
// using urlEncoding : look for NSString+URLEncoding.h implementation
if (makeUrlEncoded)
param = [param urlEncodeUsingEncoding:NSUTF8StringEncoding];
[outputStr appendFormat:#"%#=%#",key,param];
if ( px < ([dict count]-1 ) )
[outputStr appendString:#"&"];
px++;
}
return outputStr;
}
So ...
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL: baseURL
cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval: 60.f];
[request setHTTPMethod:#"GET"];
NSString* paramString = [self getQueryUrlFromDictionary:params usingUrlEncoder:YES];
NSData *postData = [paramString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
I use something like this and works fine, hope it helps

for me everything should work fine, but try this:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:"http://pretendurl.com"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET"
path:#"something"
parameters:params];

Related

How to pass multiple parameters in URL to web View in iOS?

I have following dictionary:
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
I want to send this parameters (schoolid, token, mobile) to web view. But I don't know how to send that. I tried to search on internet but I didn't get any proper solution for my question.
My main URL is:
NSString *url=#"https://MyURL.com/School/AppSingleTrack";
and I'm going to call UIWebview like following:
NSString *finalurl=[NSString stringWithFormat:#"https://MyURL.com/School/AppSingleTrack/?%#",param];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];
Try like this,
NSDictionary *param = #{#"schoolid":#"schooldb1",
#"token":del.tokenString,
#"mobile":del.phoneString
};
NSLog(#"param:%#",param);
NSString *url=#"https://24x7tracker.com/School/AppSingleTrack";
NSString *finalurl=[NSString stringWithFormat:#"https://24x7tracker.com/School/AppSingleTrack/"];
NSURL *nsurl=[NSURL URLWithString:finalurl];
NSMutableURLRequest *nsrequest=[NSMutableURLRequest requestWithURL:nsurl];
NSData *data = [NSJSONSerialization dataWithJSONObject:param options:0 error:nil];
[nsrequest setHTTPBody:data];
[_webview loadRequest:nsrequest];
[self.view addSubview:_webview];
set request's necessary properies if require like [nsrequest setHTTPMethod:#"GET"]; or POST and contentType etc.
You should use AFNetworking, It will make it more easier.
Use this Code,
NSString *sUrl = #"https://24x7tracker.com/School/AppSingleTrack";
NSMutableURLRequest *res = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sUrl]];
[res setHTTPMethod:#"POST"];
NSDictionary *params; = [NSDictionary dictionaryWithObjectsAndKeys:
#"schooldb1",#"schoolid",
del.tokenString,#"token",
del.phoneString,#"mobile",
nil];
NSMutableArray *pairArray = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in params)
[pairArray addObject:[NSString stringWithFormat:#"%#=%#", key, params[key]]];
[res setHTTPBody:[[pairArray componentsJoinedByString:#"&"] dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:res
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"request URL : %#",res.URL);
NSLog(#"request Method : %#",res.HTTPMethod);
NSLog(#"parameters : %#",params);
NSLog(#"response : %#",response);
Resp *r = [ [Resp alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:nil]];
// Success - Show Sucess message
if ([r.sCode isEqualToString:#"success"]) {
NSLog(#"response message : %#",r.sData);
}
}];
Use the Class Resp:
Resp.h
#import <Foundation/Foundation.h>
#interface Resp : NSObject
#property (nonatomic, copy) NSString *sCode;
#property (nonatomic, copy) NSString *sMessage;
#property (nonatomic, copy) NSString *sData;
- (id)initWithDictionary:(NSDictionary *)dictionary;
#end
Resp.m
#import "Resp.h"
#implementation Resp
#synthesize sCode = _id;
#synthesize sMessage = _title;
#synthesize sData = _data;
- (id)initWithDictionary:(NSDictionary *)dictionary {
self = [super init];
if (self) {
self.sCode = [dictionary objectForKey:#"code"];
self.sMessage = [dictionary objectForKey:#"message"];
self.sData = [dictionary objectForKey:#"data"];
}
return self;
}
#end
then finally get the response, hope its helpful
Firstly, talk to your colleague or check the documents of the URL, to confirm what format of parameters the API needs, and the Request method, such as GET or POST.
Secondly, concatenate the params to the proper format, and don't forget escape the parameters.
If your URL need parameters as normal, try these:
NSDictionary *params = #{#"schoolid" : #"",
#"token" : #"",
#"mobile" : #""};
NSMutableArray *keyValues = [NSMutableArray array];
for (NSString *key in params) {
[keyValues addObject:[NSString stringWithFormat:#"%#=%#&", key, params[key]]];
}
NSString *paramsString = [keyValues componentsJoinedByString:#"&"];
paramsString = [paramsString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
// Don't add / at last unless the URL has, because / is another path
NSString *baseURL = #"https://24x7tracker.com/School/AppSingleTrack";
// If GET, you can use these two lines, or use below
// NSString *urlString=[NSString stringWithFormat:#"%#?%#", baseURL, paramsString];
// NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
// if POST
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:baseURL]];
request.HTTPMethod = #"POST"; // Default is GET, you can send get request by default,
request.HTTPBody = [paramsString dataUsingEncoding:NSUTF8StringEncoding];
[webView loadRequest:request];
Edit:
According to #Shubhank's guess, if the webview's request via ajax, you should confirm the function of javascript, and try these codes in webview's delegate webViewDidFinishLoad:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"javascriptFunction(%#, %#, %#)", param1, param2, param3]];
}

How To Get Key Of goDaddy

Actually I want to created application of shortening URL , i have used GoDady by creating account at http://app.x.co/ But My URL doesnot get shorten.
This is my key
#define kGoDaddyAccountKey #"b201137c009311e6984efa163ee12fa9"
This is actually The method that do work for Shortening URL
- (IBAction)shortenURL:(id)sender
{
NSString *urlToShorten = self.webView.request.URL.absoluteString;
NSString *urlString = [NSString stringWithFormat:#"http://api.x.co/Squeeze.svc/text/%#?url=%#",kGoDaddyAccountKey,
[urlToShorten stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
shortURLData = [NSMutableData new];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
shortenURLConnection = [NSURLConnection connectionWithRequest:request
delegate:self];
}
But I get error like This.
Quite Interesting, Please Help.

XMLRPC from iOS App New Post

I am trying to add ability to my app to post a new article to a wordpress blog. I know that Wordpress has the XMLRPC, but I am having issues in implementing the wp.newPost as there is little documentation outside of Ruby PHP or JAVA.
Here is what I have in my app:
-(IBAction)postNews {
NSURL *xmlrpcURL = [NSURL URLWithString:#"https://myurl.wordpress.com/xmlrpc.php"];
NSString *username = #"email#yahoo.com";
NSString *password = #"password";
NSString *title = #"Test";
NSString *content = #"This is a test of posting to the news section from the app.";
NSString *myRequestString = [NSString stringWithFormat:#"username=%#&password=%#&content=%#", username, password, title];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: xmlrpcURL];
// set Request Type
[request setHTTPMethod: #"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",response);
}
I constantly get the response:
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>-32700</int></value>
</member>
<member>
<name>faultString</name>
<value><string>parse error. not well formed</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
What am I doing wrong with this?
Ok, for those trying to do this, documentation for Obj-C is fairly difficult to find, but here is what I did. I first imported the XMLRPC Starter Kit from here. Next, in my app I defined the server username and password as it suggests, and in my action I used both an NSDictionary and NSArray for the post to go through. Again, this is for a simple text post to a wordpress blog.
NSString *server = kWordpressBaseURL;
XMLRPCRequest *reqFRC = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
NSDictionary* filter = #{
#"post_type": #"post",
#"post_status": #"publish",
#"post_title": #"Test Title",
#"post_content": #"Test Content",
};
NSArray *postParams = #[ #0, kWordpressUserName, kWordpressPassword, filter, #[#"post_title"]]; [reqFRC setMethod:#"wp.newPost" withObjects:postParams];
//The result for this method is a string so we know to send it into a NSString when making the call.
NSString *result = [self executeXMLRPCRequest:reqFRC];
[reqFRC release]; //Release the request
//Basic error checking
if( ![result isKindOfClass:[NSString class]] ) //error occured.
NSLog(#"demo.sayHello Response: %#", result);
Obviously, you can have text fields that you pull from for your blog post content, but this worked great!
U can add new posts using xmlrpc as given code
XMLRPCRequest *req = [[XMLRPCRequest alloc] initWithURL:[NSURL URLWithString:#"your url name"]];
NSArray *yourparameter = #[#0,#"your user id",#"your password"];
[request setMethod:#"wp.newPost" withParameters:yourparameter];
XMLRPCResponse *saveRessponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req error:nil];
NSLog(#"The Response is%#",[saveRessponse object]);
You can add new post using xml-rpc as
XMLRPCRequest *reqFRC = [[XMLRPCRequest alloc] initWithURL:[NSURL URLWithString:#"your url name"]];
// Set your url here.
NSArray *params = #[#0,#"your user id",#"your password"];
// Add your url parameters here.
[request setMethod:#"wp.newPost" withParameters:params]; // To add new post.
XMLRPCResponse *nodeSaveRessponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:request error:nil];
NSLog(#"server response :%#",[nodeSaveRessponse object]);

How to get cookie from a url in iOS?

I have an application where I have to create session using a URL and need to get cookie from that URL and pass the cookie to webview so that it won't ask for any username and password.
For that I am using this code:
- (void)getcookie {
NSURL* aUrl =
[NSURL URLWithString:#"https://www.sessioncheck.com/session/create"];
NSMutableURLRequest* request =
[NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSString* email = #"tina#gmail.com";
NSString* password = #"abcde#123";
NSString* combinedString =
[NSString stringWithFormat:#"%#:%#", email, password];
NSString* base64encodedstring =
[NSString stringWithBase64EncodedString:combinedString];
NSData* base64data = [NSData dataWithBase64EncodedString:combinedString];
[request addValue:[NSString stringWithFormat:#"Basic %#", base64encodedstring]
forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError* error = nil;
NSData* returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
if (returnData != nil) {
NSDictionary* JSONDictionary =
[NSJSONSerialization JSONObjectWithData:returnData
options:kNilOptions
error:&error];
}
}
This is my Android code. I am able to get cookie in Android:
HttpGet get;
try {
get = new HttpGet(
new URI("https://www.sessioncheck.com/session/create"));
byte[] encodedBytes = Base64.encodeBase64((email+":"+password).getBytes());
//System.out.println("encodedBytes " + new String(encodedBytes));
get.setHeader("Authorization", "Basic " + new String(encodedBytes));
http.execute(get);
List<Cookie> cookies = ((DefaultHttpClient)http).getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
}
String cookieString = cookie.getName() + "=" + cookie.getValue();
signedin.storeCookie("cookie", cookieString);
}
I am trying to get the base64encoded string from my combinedString(username:password) but the problem is my base64encodedstring is returning nil.
Did you use this code: https://github.com/nicklockwood/Base64 ?
If you did then you should use - (NSString *)base64EncodedString; instead.
So your code should look like this:
NSString* base64encodedstring = [combinedString base64EncodedString];
NSData* base64data = [base64encodedstring dataUsingEncoding:NSUTF8StringEncoding];
About cookies, you can get them from "returningResponse" outgoing parameter of -[NSURLConnection sendSynchronousRequest:returningResponse:error:].
You should pass an address of a NSHTTPURLResponse pointer into it.
So your code should be like this:
NSHTTPURLResponse *res = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&res
error:&error];
NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[res allHeaderFields]
forURL:aUrl];
EDIT : As you requested, to set cookies into a NSMutableURLRequest, you have to use the NSArray *cookies from above. Here is the code:
// Use the cookies from the code above
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:newURL];
[req setAllHTTPHeaderFields:headers];
// Do your other setups here...

How to send multiple parameterts to PHP server in HTTP post

I'm sending base64 string to php server and its working well. Now I want to send another parameter as a string. Can anyone tell me what code need to add in below code.
Below code is working good for single parameter. How can we modify it for multiple parameters?
NSData *data = [UIImageJPEGRepresentation(imgeview.image,90) base64Encoding];
// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:#"question_image=%#",data];
myRequestString = [myRequestString stringByReplacingOccurrencesOfString:
#"+" withString:#"%2B"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String]
length:[myRequestString length]];
request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://192.168.0.101/Mobile_tutor/webservice/question_details.php"]];
// set Request Type
[request setHTTPMethod:#"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody:myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes]
length:[returnData length]
encoding:NSUTF8StringEncoding];
NSLog(#"-------------%#",response); // here you get reasponse string
For the network operation these is better supporting API like AFNetworking available witch work async and way better to handle
Tutorials for AFNetworking
Get from here
NSArray *keys = #[#"UserID", ];
NSArray *objects = #[#(userId)];
NSDictionary *parameter = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:
[NSURL URLWithString:BaseURLString]];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"services/UserService.svc/GetUserInfo"
parameters:parameter];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError* error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if ([jsonObject isKindOfClass:[NSDictionary class]]) {
// do what ever
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Given a NSDictionary "params" whose keys and values are strings and where every entry represents one parameter (name/value) you can define a helper category:
#interface NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded;
#end
dataFormURLEncoded returns a properly encoded character sequence from the given parameters in the dictionary.
The encoding algorithm is specified by w3c: URL-encoded form data / The application/x-www-form-urlencoded encoding algorithm
It can be implemented as follows:
First, a helper function which encodes a parameter name, respectively a parameter value:
static NSString* x_www_form_urlencoded_HTML5(NSString* s)
{
// http://www.w3.org/html/wg/drafts/html/CR/forms.html#application/x-www-form-urlencoded-encoding-algorithm , Editor's Draft 24 October 2013
CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?#~");
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(__bridge CFStringRef)s,
charactersToLeaveUnescaped,
legalURLCharactersToBeEscaped,
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
Finally, dataFormURLEncoded composes the character sequence of the encoded parameters. A "parameter" will be composed by concatenating the encoded name, = and encoded value:
parameter := name "=" value
Then, the parameter list will be composed by concatenating the parameters by separating them by a "&":
parameters := parameter ["&" parameter]
It can be implemented as below:
#implementation NSDictionary (FormURLEncoded)
-(NSData*) dataFormURLEncoded {
NSMutableData* data = [[NSMutableData alloc] init];
BOOL first = YES;
for (NSString* name in self) {
#autoreleasepool {
if (!first) {
[data appendBytes:"&" length:1];
}
NSString* value = self[name];
NSData* encodedName = [x_www_form_urlencoded_HTML5(name) dataUsingEncoding:NSUTF8StringEncoding];
NSData* encodedValue = [x_www_form_urlencoded_HTML5(value) dataUsingEncoding:NSUTF8StringEncoding];
[data appendData:encodedName];
[data appendBytes:"=" length:1];
[data appendData:encodedValue];
first = NO;
}
}
return [data copy];
}
#end
Note: The character sequence encodes the strings using Unicode UTF-8.
Example:
Given your parameters:
NSDictionary* params = #{#"a": #"a a", #"b": #"b+b", #"c": #"ü ö"};
NSData* encodedParamData = [params dataFormURLEncoded];
Now, encodedParamData will be added to your body whose content type is application/x-www-form-urlencoded.
The encoded parameter string becomes:
a=a+a&b=b%2Bb&c=%C3%BC+%C3%B6

Resources