How to add query string to every url request of NSURLSession. All request will have the same query string.
How to append this?
Below is the way to send the string to every request URL
NSString *stringURL=[NSString stringWithFormat:#"%#%#%#",baseUrl,#"/API/URL/",your parameter];
// Allocate and initialize an NSURLConnection with the given request and delegate. The asynchronous URL load process is started as part of this method.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:stringURL] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
Related
I know I can use the below code to change the default agent:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"Your user agent", #"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
but I want to request a different User-Agent for different requests. Examples: request 'www.google.com', use agent=‘google Agent’, request 'www.github.com', use agent='github Agent'.
I have tried the below way to set the 'User_Agent' in each request, but it doesn't seem to work.
- (void)viewDidLoad {
NSString *urlAddress = #"http://www.amazon.com";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];
//URL Requst Object
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
[requestObj setValue:#"Foobar/1.0" forHTTPHeaderField:#"User_Agent"];
// But the value is not "Foobar/1.0"
NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:#"navigator.userAgent"];
NSLog(#"agent - %#", secretAgent);
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
One more question:
It seems a change to the default agent only work change in 'AppDelegate' or 'initialize'. Am I right? Because I try to change in 'viewDidLoad' but it doesn't seem to work.
I observed that if you load any url in webView with a user-agent set
to it. After some time you load the different url & different user
agent but used the same allocated WebView instane.The web view will
load the new url but can not set new user-agent. It just set old one
that you have set before loading first time.
You can not change untill you initiate new instanse of UIWebview(or
we can say that user agent can be set once per session). So I coame to result that user-agent can be set only once.
What I did for this problem is, I allocated new instance when I want set new user-agent.
You don't need to set it using JavaScript.
You have misspelled User-Agent. Use this minimal code taken from here
NSString* userAgent = #"My Cool User Agent";
NSURL* url = [NSURL URLWithString:#"http://whatsmyuseragent.com/"];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:userAgent forHTTPHeaderField:#"User-Agent"];
I want to send some data via http post from my App to the server. All symbols can be accepted by the server, except the &.
the server is php;
content-type is application/x-www-form-urlencoded, and charset is utf-8.
Encoding is NSUTF8StringEncoding.
I tried also changing the & with URLEncoding, i.e. & --> %26. the server can receive it, but cannot display it recht. It's shown in %26, not &.
But, the server can properly received and displayed, if it is sent by android or web side.
The code is the following:
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"xxx.com/server.php"]];
postRequest.HTTPMethod = #"POST";
[postRequest setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSString *bodyString = [NSString stringWithFormat:#"data=&&&&"];
postBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
NSURLConnection *postConnect = [[NSURLConnection alloc]initWithRequest:postRequest delegate:self];
hope this helps you
NSString *encodedString = [myString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
It won't replace your string inline; it'll return a new string. That's implied by the fact that the method starts with the word "string". It's a convenience method to instantiate a new instance of NSString based on the current NSString.
Note--that new string will be autorelease'd, so don't call release on it when you're done with it.
It should be with the function
(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)url, NULL, (CFStringRef)#"&", kCFStringEncodingUTF8))
I am working on an iPhone app project now which implements some connections using NSURLRequests using cachePolicy:NSURLCacheStorageNotAllowed (I am using ios 7).
But it seems like the responses are still cached and I get old responses for the same URL call. In spite of having the cache policy as "cachePolicy:NSURLCacheStorageNotAllowed".
Why is it still caching the responses? Is the issue still present in the latest release?
The correct enum for the cache Policy iOS7 is as described below:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:downloadURL
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
If you are over 3G, some provider use caching even if you disable it in your NSMutableURLRequest, so if the cache policy doesn't work then set the http header field cache-control to no-cache.
[request setValue:#"no-cache" forHTTPHeaderField:#"cache-control"];
Here the enum list check your header NSURLRequest.h for the correct up to date enum :)
enum
{
NSURLRequestUseProtocolCachePolicy = 0,
NSURLRequestReloadIgnoringLocalCacheData = 1,
NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented
NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData,
NSURLRequestReturnCacheDataElseLoad = 2,
NSURLRequestReturnCacheDataDontLoad = 3,
NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented
};
typedef NSUInteger NSURLRequestCachePolicy;
The correct answer for a non cached request should be NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:downloadURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; since NSURLRequestReloadIgnoringLocalAndRemoteCacheData it's unimplemented.
From https://developer.apple.com/reference/foundation/nsurlrequestcachepolicy/nsurlrequestreloadignoringlocalcachedata?language=objc
I need to send a image to server with Url the url looks as below
http://somewebsite.com:8080/app/api/fappname/newUser/1/Delhi481/cct/12 dk/11588/kmkr/72579/Los/TM/8:00/13:00/28.6100/77.2300/foto1.jpg/null
they asked me to send image in place of foto1.jpg, the code that now i'm using is as below i am sending null inplace of image i'm getting response. can any one send me how to send the image in this url.
NSString *str = [NSString stringWithFormat:#"http://someurl.com:8080/app/api/kkknnmm/newUser/1/%#/%#/%#/%#/%#/%#/%#/TM/%#/%#/%#/%#/%#/%#/%#",[inSchoolName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],#"kktt",[inAddressStreet stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],inAddressNo,inAddressState,inZipCode,[inNeighbourhood stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[arrivalHR stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[endingHr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],inlat,inlong,inImg1,inImg2,inImg3];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str]];
NSLog(#"Login Url:%#",str);
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
can any one please help me.
Well your Api Is expecting binary data, I would suggest you to go through these links.
I hope they Will Help you.
Have A look at this And this
I have succeeded in making a post using a HTTP Client by setting the content type as application/json and this json code:
{
"order": {
"name": "Tia Carter",
"location": "Corams",
"phone_number": "707",
"food": "Bobcat Burger"
}
}
The code works perfect and the order is registered in the database. I am trying to work this into my iOS app but keep getting syntax errors regarding the colons in the json. This is the objective-c code:
NSURL *nsURL = [[NSURL alloc] initWithString:#"http://0.0.0.0:3000/orders.json"];
NSMutableURLRequest *nsMutableURLRequest = [[NSMutableURLRequest alloc] initWithURL:nsURL];
// Set the request's content type to application/x-www-form-urlencoded
[nsMutableURLRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Set HTTP method to POST
[nsMutableURLRequest setHTTPMethod:#"POST"];
// Set up the parameters to send.
NSString *paramDataString = [NSString stringWithFormat:#
"{ "order": {"%#:" ="%#","%#:"="%#","%#:"="%#","%#:"="%#"}}", #"name", _name.text, #"location", _location.text, #"phone_number", _phoneNumber.text, #"food", _order.text];
// Encode the parameters to default for NSMutableURLRequest.
NSData *paramData = [paramDataString dataUsingEncoding:NSUTF8StringEncoding];
// Set the NSMutableURLRequest body data.
[nsMutableURLRequest setHTTPBody: paramData];
// Create NSURLConnection and start the request.
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]initWithRequest:nsMutableURLRequest delegate:self];
I'd appreciate any ideas or guidance. Thanks.
I believe you have two problems:
You didn't escape quotas (put \ before all of them)
You don't need to put text "name", "location" and etc in parameters (it's not a problem per se, just a style thing)
Also, I would recommend to work with NSDictionary and convert it to JSON when you need to (it will save you a lot of nerves for unescaped quotas, missing bracket and so on).
Look this question how to convert NSDictionary to JSON:
Generate JSON string from NSDictionary in iOS