I am trying to post a string to a server using the next example:
// 1
NSURL *url = [NSURL URLWithString:#"YOUR_WEBSERVICE_URL"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3
NSDictionary *dictionary = #{#"key1": #"value1"};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:kNilOptions error:&error];
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
}];
// 5
[uploadTask resume];
}
The difference is that I don't have a NSDictionary But an NSString object that stores an array of dictionaries, and also the string that I post must not be encoded it must be a simple string, so it is visible in the search field if I manually enter it.
My NSString example:
[{
"api_id" = debugger;
at = "2015-02-05T01:41:13Z";
oS = IOS;
ver = "8.10";
what = "showAdAt: forViewController:";
},
{
"api_id" = debugger;
at = "2015-02-05T01:41:13Z";
oS = IOS;
ver = "8.10";
what = "showAdAt: forViewController:";
}
]
Thank you in advance and be patient with me as this is my first post attempt.
I was thinking that the above example should work for me if I first convert the NSString to NSArray with dictionaries as objects.
UPDATE:
Currently I am trying to post the string as:
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{
#"Authorization" : #"CUSTOM AUTHORIZATION THAT I AM USING",
#"Content-Type" : #"application/json"
};
// Create the session
// We can use the delegate to track upload progress
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
// Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
NSURL *url = [NSURL URLWithString:#"MY WEBSITE LINK"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
//Convert the string to NSData
bodyContainerString = #"[{\"api_id\":\"A124\",\"at\":\"2011-04-10T20:09:31Z\",\"os\":\"ANDROID\",\"ver\":\"2.1\",\"what\":\"TEST\",\"value\":\"\"},{\"api_id\":\"A124\",\"at\":\"2011-04-10T20:10:31Z\",\"os\":\"ANDROID\",\"ver\":\"2.1\",\"what\":\"TEST\",\"value\":\"\"}]";
NSData* jsonData = [bodyContainerString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [jsonData subdataWithRange:NSMakeRange(0, [jsonData length] - 1)];
NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(newStr);
request.HTTPBody = jsonData;
NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Process the response
NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 201) {
//if no error on upload then delete content of plist
NSLog(#"Success on post1");
}
NSLog(#"Success on post2");
}];
[uploadTask resume];
Update 2, the resulting link should look like:
curl -X POST http://MY_LINK/smtg -H 'Authorization: CUSTOM_FIRST_HEADER' -H "Content-Type: application/json" -d '[{"api_id":"A124","at":"2011-04-10T20:09:31Z","os":"ANDROID","ver":"2.1","what":"TEST","value":""},{"api_id":"A124","at":"2011-04-10T20:10:31Z","os":"ANDROID","ver":"2.1","what":"TEST","value":""}]'
I ended up using the first example that I found here is my implementation:
NSURL *url = [NSURL URLWithString:#"MY_LINK/smtg"];
//Create thhe session with custom configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{
#"Authorization" : [NSString stringWithFormat:#"BEARER %#",finalToken],
#"Content-Type" : #"application/json"
};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3
NSError *error = nil;
NSData* jsonData = [bodyContainerString dataUsingEncoding:NSUTF8StringEncoding];
if (!error) {
// 4
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:jsonData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
}];
// 5
[uploadTask resume];
}}
Related
Hi am new to development I need to post the below array in a url kindly guide me to solve this issue.
{
"order": {
"email": "foo#example.com",
"fulfillment_status": "fulfilled",
"send_receipt": true,
"send_fulfillment_receipt": true,
"line_items": [
{
"variant_id": 447654529,
"quantity": 1
}
]
}
}
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
[sessionConfiguration setAllowsCellularAccess:YES];
[sessionConfiguration setHTTPAdditionalHeaders:#{ #"Accept" : #"application/json" }];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSString *datastring = #"{\"order\": {\"email\": \"foo#example.com\",\"fulfillment_status\": \"fulfilled\",\"send_receipt\":true,\"send_fulfillment_receipt\": true,\"line_items\": [{\"variant_id\": 447654529,\"quantity\": 1}]}}";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"YOUR LINK"]];
NSLog(#"url=%#",url);
// Configure the Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPBody = [datastring dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = #"POST";
// post the request and handle response
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
// Handle the Response
if(error)
{
NSLog(#"%#",[NSString stringWithFormat:#"Please check your internet connection: %#", [error description]]);
// Update the View
dispatch_async(dispatch_get_main_queue(), ^{
// Hide the Loader
// [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] delegate].window animated:YES];
[self ShowConnectionError];
});
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"retVal=%#",retVal);
});
}];
// Initiate the Request
[postDataTask resume];
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
When I try to call web service using NSURLSession with POST on Apple Watch, response parameter is nil. What might be the issue with this ?
Code for calling web service:
NSURL *url = [NSURL URLWithString:#"https://demo.test.com:22322/api/Alerts/UpdateAlertStatus?intUserId=5¶maccessTokenId=24460c5f-be71-45b5-99cf-f46c277c3d9e&UserId=100200"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSMutableDictionary *mutDictParameters = [[NSMutableDictionary alloc] init];
[mutDictParameters setObject:#"708" forKey:#"AlertId"];
[mutDictParameters setObject:#"2878" forKey:#"XmlMessageId"];
[mutDictParameters setObject:#"5" forKey:#"UserId"];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:mutDictParameters
options:kNilOptions error:&error];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
NSLog(#"Response : %#",response);
}];
[uploadTask resume];
}
I`m trying to send JSON via HTTP Request:
Here is my code :
NSString* locations = [kBaseURL stringByAppendingPathComponent:kLocations];
BOOL isExistingLocation = location._id != nil;
NSString *urlStr = isExistingLocation ? [locations stringByAppendingPathComponent:location._id] : locations;
NSURL* url = [NSURL URLWithString:urlStr]; //1
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
NSData* data = [NSJSONSerialization dataWithJSONObject:[location toDictionary] options:0 error:NULL]; //3
request.HTTPBody = data;
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"]; //4
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
if (!error) {
NSLog(#"%#", response.description);
NSArray* responseArray = #[[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
[self parseAndAddLocations:responseArray toArray:self.objects];
}
}];
[dataTask resume];
and here is the dictionary which I`m trying to send...
http://www.imageupload.co.uk/image/5YUE
EDIT: I configured the server to return the HTTPBody received and the return is
{}
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.