i'm trying to send a POST request to my server with the following code:
NSURLSessionConfiguration *defaultConfigObj = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObj];
//NSURL *url = [NSURL URLWithString:#"http://www.myserver.com/page.aspx"];
NSURL *url = [NSURL URLWithString:#"http://10.47.72.40/test/page.aspx"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.10f];
NSString *params = [NSString stringWithFormat:#"data=%#&UserMail=%#",
InfoDictionary[#"ID"],
arrDatosMail[0]
];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response: %# error:%#", response, error);
if(error == nil){
NSString *textRepsonse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", textRepsonse);
}
}];
So, when a try with the local IP, it works fine (the server receives the POST request), but when I change the remote IP (with de www.myserver.com/page.aspx) the page receives the request with GET method, i don't know why :(,
What i'm doing wrong? Thanks in advance.
There is no problem. Request will be sent as POST.
I would recommend to use proxy to debug what is send exactly. On Mac Charles proxy is good one.
Charles proxy web site
Related
How to make HTTP Post request with JSON body in Swift like in this there are not using frameworks like this i need xml posting can any one help me...
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"Your SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:#"application/xml" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSString *xmlString = #"<?xml version=\"1.0\"?>\n<yourdata></yourdata>";
[request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handel response & error
}];
[postDataTask resume];
Use the above code to achieve what you want
When i am using NSURLSession while Posting through the Browser is returning the result as 200 status but when i send it through code in IOS i am getting 500 status code as below.
Response:<NSHTTPURLResponse: 0x14e754240> { URL: urlAPI } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 30;
"Content-Type" = "text/plain; charset=utf-8";
Date = "Thu, 28 Jan 2016 12:59:10 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }
Below is my code
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"HERE IS MY URL"];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString * params =#"MY PARAMETERS";
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[dataTask resume];
This code worked previously but it is throwing error now(API code also not changed),where am i doing wrong.Help me out of this.
Try to send the parameters in NSDictionary:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#“[Your SERVER 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"];
NSDictionary *postData = [[NSDictionary alloc] initWithObjectsAndKeys: #“TestUservalue”, #"name",
#“TestPassvalue”, #“password”,
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject: postData options:0 error:&error];
[request setHTTPBody: postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
The problem is with the parameters that you are sending to your webserver. They must be properly encoded. I was having the same 500 status code.
I was able to fix my problem by changing my post parameters. I removed the _ from my post variables name and it worked.
NSString * params = [NSString stringWithFormat:#"q_id=%#&c_id=%#&agent=%#",self.q_id, self.c_id, agent];
// changed to
NSString * params = [NSString stringWithFormat:#"qid=%#&cid=%#&agent=%#",self.q_id, self.c_id, agent];
Also check out this link on Objective-C encoding
Good day.Im trying to send simple post data to server.This is the code how i do it.
-(void)makeRequest:(NSString*)stringParameters{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://vaenterprises.webatu.com/Authentication.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/text" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/text" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString* postData = #"tag=hello&username=yo&something=something";
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[self parseJson:data];
}];
[postDataTask resume];
}
It looks great till i echo the whole post from php side like this
echo json_encode($_POST);
and i print the result in the iOS like this
-(void)parseJson:(NSData*) data{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary* jsonObject= [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
NSLog(#"%#",myString);
}
this issue is that i get empty string..so it means that post data not being send and that is 10000 percent objective c side issue and i have no clue why its so as in this method we only got setHttpBody with the actual string which contains key and value separated by & but that data not being send as you can see.So what am i doing wrong?Please tell somebody
Http body has to be of type NSData. Try out following code
NSString* stringData = #"tag=hello&username=yo&something=something";
NSData* data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
I'm struggling translating these cURL requests into Objective - C (I'll change the API keys later):
Get request:
curl -v -H "app_id:4bf7860a" -H "app_key:0026e51c7e5074bfe0a0c2d4985804b2" -X GET "http://data.leafly.com/strains/blue-dream"
Post request:
curl -v -H "app_id:4bf7860a" -H "app_key:0026e51c7e5074bfe0a0c2d4985804b2" -X POST "http://data.leafly.com/strains" -d '{"Page":0,"Take":10}'
I've been able to get one successful request so far:
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"http://data.leafly.com/strains/blue-dream"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField: #"Content-Type"];
[request addValue:#"4bf7860a" forHTTPHeaderField: #"APP_ID"];
[request addValue:#"03d3eaa965c5809c5ac06a25505a8fe4" forHTTPHeaderField:#"APP_KEY"];
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Data: %#",data);
if (error) {
NSLog(#"ERROR: %#", error);
} else {
NSDictionary *jSONresult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Strain %#",jSONresult);
}
}];
[task resume];
I'm just not able to piece together a comprehensive way to piece together these request consistently (I've tried http://unirest.io/objective-c.html). Can anyone point me to a good resource or help me think through what I'm doing wrong?
Check the code snippet out below that should definitely help.
NSString *Post = [[NSString alloc] initWithFormat:#"{Page:0, Take:10}"];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:#"http://data.leafly.com/strains"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req addValue:#"a2eaffe2" forHTTPHeaderField: #"app_id"];
[req addValue:#"49588984075af3d275a56c93b63eedc0" forHTTPHeaderField:#"app_key"];
[req setHTTPBody:PostData];
NSData *res = [NSURLConnection sendSynchronousRequest:req returningResponse:NULL error:NULL];
NSString *myString = [[NSString alloc] initWithData:res encoding:NSUTF8StringEncoding];
NSLog(#"%#", myString);
I must be missing something basic because I am unable to get any NSURLSession examples using POST to work at all. I have my server set up to print out (to a file that I tail) all the received POST parameters and nothing I put in the POST body shows up. I've tried the solutions from Send POST request using NSURLSession as well as online tutorials such as the Ray Wenderlich Cookbook for using NSURLSession.
Here, for example, is the code almost directly from the Stackoverflow thread, mentioned above, with only the URL and the post arguments changed:
-(void)postTest {
NSString *textContent = #"XXXXX";
NSString *noteDataString = [NSString stringWithFormat:#"x=%#", textContent];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{
#"a" : #"YYYYY"
};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURL *url = [NSURL URLWithString:#"[MY URL with PHP script]"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = #"POST";
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
outputLabel.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
}
The PHP script shows the "XXXXX" parameter was properly received - but it's not part of the POST body; rather, it is part of the URL itself. The only parameter in the POST body is the "YYYYY" parameter but it doesn't show up at all.
The Ray Wenderlich example didn't work either: nothing showed up for the PHP script.
-(void)testPost {
NSURL *url = [NSURL URLWithString:#"[MY URL with PHP script]"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSDictionary *dictionary = #{#"a": #"YYYYY"};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
if (!error) {
NSURLSessionUploadTask *uploadTask =
[session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
}];
[uploadTask resume];
}
}
Is there something I'm not setting somewhere? I hadn't expected the shift to NSURLSession would have such subtle boobytraps and I'm wondering if it's something silly I'm doing wrong or missing. Thanks for any help!
Apple Documentation about the request parameter on uploadTaskWithRequest:fromData:completionHandler:
An NSURLRequest object that provides the URL, cache policy, request
type, and so on. The body stream and body data in this request object
are ignored.