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
{}
Related
I am working in an application in which I have to send image to the server, I am trying to send Image to server but in return I am getting
BAD REQUEST 400
. Please tell me how do I resolve this error.
This method is use to convert image into base64 string
NSData * imagedata = UIImageJPEGRepresentation(chosenImage, 0.5);
NSString * base64String = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength
-(void)temp
{
NSString * str=[self base64return];
NSDictionary* jsonDict = #{
#"name": #"image_name",
#"img_data":str
};
NSData * postData = [NSJSONSerialization dataWithJSONObject:jsonDict
options:kNilOptions error:nil];
NSURL * url=[NSURL URLWithString:#"http://xxxxxx/finalresult1"];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (error == nil)
{
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
NSString * text = [[NSString alloc] initWithData: data encoding:
NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSLog(#"erroer is %#",error);
}
else
{
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
Change request Content-Type, Use:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *URLString = #"http://api.sandbox.africastalking.com/version1/airtime/send";
NSString *encodedString = [URLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:encodedString];
NSDictionary *body = #{
...
};
// convert the dictionary into json data
NSError *error;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
// Create a post request with the json as a request body.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = #"POST";
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
request.HTTPBody = JSONData;
// create the task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSLog(#"Status code: %li", (long)((NSHTTPURLResponse *)response).statusCode);
NSLog(#"Response: %#", response);
NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response Text: %#", responseText);
} else {
NSLog(#"Error: %#", error.localizedDescription);
}
}];
[task resume];
The code returns "The requested resource could not be found" 404 as response but when I try this request in my REST client (Postman) it works fine.
Try a url with the URLWithString method
NSURL *url = [NSURL URLWithString:#"http://api.sandbox.africastalking.com/version1/airtime/send"];
hello all i know this kind of question asked previously but i didn't get any solution from them
in my project i am working in login view when i am put code on login button i am getting an error
Error : Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x7fb37b62c9a0 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x7fb37b715a20 "The operation couldn’t be completed.
(kCFErrorDomainCFNetwork error -1002.)"}
but i am using the same code for login which i used in my previous projects and it works fine there
here is my code:
-(IBAction)login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php?token={LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUc4d0RRWUpLb1pJaHZjTkFRRUJCUUFEWGdBd1d3SlVBeWo0WE9JNjI4cnJRTG9YeEpXNG1zUWI1YmtvYk1hVQpzMnY1WjFKeXJDRWdpOVhoRzZlZk4rYTR0eGlMTVdaRXdNaS9uS1cyL1NCS2pCUnBYUzVGYUdiV0VLRG1WOXkvCkYrWHhsUXVoeER0MEV3YkRBZ01CQUFFPQotLS0tLUVORCBQVUJMSUMgS0VZLS0tLS0K}&method=user.getLogin"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"login=abc#gmail.com&password=123456"];//,username.text, password.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"map data is = %#",mapData);
NSURLSessionDataTask * postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * data, NSURLResponse* response, NSError * error) {
if(error == nil)
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"jsondic= %#",jsonDic);
NSDictionary *userDataDic = [jsonDic objectForKey:#"data"];
NSLog(#"Dict is %#",userDataDic);
Please help me to resolve it i already see the similar type of questions but didn't overcome from this issue
Any help is appreciated
I tried your code.Except your url the other lines of code is correct.If you pass your corrct URL,it works perfectly.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://eyeforweb.info.bh-in-15.webhostbox.net/myconnect/api.php"]]; //pass your url here
[request setHTTPMethod:#"POST"];
//Passing The String to server
NSString *strUserId = #"pradeep.kumar#eyeforweb.com";
NSString *strPassword = #"admin123";
NSString *userUpdate =[NSString stringWithFormat:#"login=%#&password=%#",strUserId,strPassword, nil];
//Check The Value what we passed
NSLog(#"the data Details is %#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"The postData is - %#",data1);
//Apply the data to the body
[request setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"Login SUCCESS");
}
else
{
NSLog(#"Login FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
I tried to add an entry to db using a POST request in Objectve-C. My service is:
#RequestMapping(method = RequestMethod.POST, headers = "content-type=application/json")
public
#ResponseBody
boolean addEmployee(#ModelAttribute User user) {
try {
logger.log(Level.INFO, user.getCountry());
userDataService.addUser(user);
return true;
//return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
e.printStackTrace();
return false;//new Status(0, e.toString());
}
}
When I try this on Postman, it's working fine with x-www-form-urlencoded. But when I try this in Objective-C, nothing happens. Here is what I tried:
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:#"POST"];
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[rq setValue:[NSString stringWithFormat:#"%ld", (long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSLog(#"%#", [error localizedDescription]);
}];
In completion block, the log prints "Could not connect to the server". How can I call the service with JSON data?
Something like this should work
// 1: Create your URL, Session config and Session
NSString *jsonInputString = #"{\"userName\":\"abcd\"}";
NSString *jsonRequest = jsonInputString;
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/user"];
NSURLSessionConfiguration *config =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
// 2: Create NSMutableRequest object
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
// 3: Create Jsondata object
NSError *error = nil;
NSData *jsonData = [jsonInputString dataUsingEncoding:NSUTF8StringEncoding];
// Asynchronously Api is hit here
NSURLSessionUploadTask *dataTask =
[session uploadTaskWithRequest:request
fromData:data
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
NSLog(#"%#", data);
NSDictionary *json =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
NSLog(#"%#", json);
success(json);
}];
[dataTask resume]; // Executed First
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];
}}