In my project I make the other functions work with this code. But for this method I cannot make it work. I did copy-paste all this code for different methods(changing URL ,Result). The parameters of this methods are only int and string.
I always correct the wcf method from SOAP UI and .NET project.It works correct.
I only cannot make this code work for this method.
The [request responseString] returns a patient's information. Please help me. Thank you.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:HASTAARAIP]];
NSData *myPostData = [[NSString stringWithFormat:#"{\"kat\":0,\"oda\":0,\"hastaAdi\":\"KAI\",\"protokolNo\":0,\"yatanAyaktan\":1}"] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *myMutablePostData = [[NSMutableData alloc]initWithData:myPostData];
[request setPostBody:myMutablePostData];
[request setRequestMethod:#"GET"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startSynchronous];
Here is some things that can make you understand.
With this code the [request responseString] and [request responseStatusMessage] is null. But if I remove the line where the addRequestHeader, it says for responseStatusMessage HTML/1.1HTTP/1.1 404 Not Found 404. I didn't understand why it gives this 404 error. This request type works for the other methods.
The ıp is like http://.../rest/<methodname>
Added log for a part of responsestring`:
The server encountered an error processing the request. The exception
message is 'The incoming message has an unexpected message format
'Raw'. The expected message formats for the operation are 'Xml';
'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See the documentation of
WebContentTypeMapper for more details.'. See server logs for more
details. The exception stack trace is:
Updated:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:HASTAARAIP]];
[request setPostValue:#"0" forKey:#"kat"];
[request setPostValue:#"0" forKey:#"oda"];
[request setPostValue:#"KAI" forKey:#"hastaAdi"];
[request setPostValue:#"0" forKey:#"protokolNo"];
[request setPostValue:#"1" forKey:#"yatanAyaktan"];
[request startSynchronous];
But for responseString the logs:
The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml'; 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is:
Trying with AFNetworking:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"kat": #"0",#"oda": #"0", #"hastaAdi":hastaAdi, #"protokolNo":#"0",#"yatanAyaktan":#"1"};
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[manager POST:HASTAARAIP parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But the log is like this:
Error: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x8e49ce0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
ASI was long abandoned by the developer. using AFNetworking 2.0 will be more easy, and with a lot of good documentation: https://github.com/AFNetworking/AFNetworking
it looks like you are trying to make a #"POST" request.
you can use the following code snippet (uses IOS build in classes) to make the request:
NSDictionary *parameters = #{#"key" : value};
/* the following serialization is NOT a deep serialization */
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://www.someURL.com/whatEver"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(#"all headers from response:%#", [httpResponse allHeaderFields]);
NSLog(#"status code from response:%ld", (long)[httpResponse statusCode]);
}
}];
Related
I am having an issue in making a call to our RESTful API. The request is to get the token from the API; I need that token to use it to make further calls on that API.
The issue is that whenever I make that call, I get HTTP 403 status code and I don't know why. I am making the same calls from Android but they work fine without any issue.
Actually I have no experience at all to work with xCode; I am just implementing some changes in the existing code which was written by some other developer. I don't know if I am doing something wrong or what.
id keys[] = {#"grant_type", #"client_id", #"client_secret", #"username", #"password"};
id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"https://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if(data.length > 0 && connectionError == nil) {
NSLog(#"Response --> %# ", response);
}
}
];
Can someone try to help me figure out what is actually going wrong?
Thanks in advance.
I ran your code and the log, i am getting is
Error Domain=NSURLErrorDomain Code=-1003 "A server with the specified
hostname could not be found." UserInfo=
{NSUnderlyingError=0x608000059aa0 {Error Domain=kCFErrorDomainCFNetwork
Code=-1003 "A server with the specified hostname could not be found."
UserInfo={NSErrorFailingURLStringKey=http://oauth-
test.websitename.com/token, NSErrorFailingURLKey=http://oauth-
test.websitename.com/token, _kCFStreamErrorCodeKey=8,
_kCFStreamErrorDomainKey=12, NSLocalizedDescription=A server with the
specified hostname could not be found.}},
NSErrorFailingURLStringKey=http://oauth-test.websitename.com/token,
NSErrorFailingURLKey=http://oauth-test.websitename.com/token,
_kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8,
NSLocalizedDescription=A server with the specified hostname could not
be found.}
I tried it with NSUrlSession also but it is giving same problem.
I think your server is not configured
Below is the code with URL session
id keys[] = {#"grant_type", #"client_id", #"client_secret",
#"username", #"password"}; id objects[] = {#"password", #"AppClientID", #"AppClientSecret", #"usernamehere", #"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id); NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"Basic" forHTTPHeaderField:#"Authorization"]; [request setHTTPBody:jsonData];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDownloadTask *dataTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(#"%#", response);
}];
[dataTask resume];
Am unable to find the real problem with my code. Am using the same code for all other APIs and everything working fine but one API is giving problem.
NSString *strUrl = [[NSString stringWithFormat:#"%#%#",baseURL,apiURL] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
//request type may be "POST" or "GET"
[request setHTTPMethod:requestType];
[request setValue:secretKey forHTTPHeaderField:key];
//contentType may be "application/json" or "text/html"
[request setValue:contentType forHTTPHeaderField:#"Accept"];
[request setValue:contentType forHTTPHeaderField:#"Content-Type"];
AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.responseSerializer = [AFJSONResponseSerializer serializer];
[requestOperation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
completion(nil);
}];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
completion(nil);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
completion(nil);
}];
This code is working for all APIs except one. It's giving me this error in error block.
Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
I have then tried to add the acceptable content type by doing this.
requestOperation.responseSerializer.acceptableContentTypes = [requestOperation.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
This did not work. Then i changed the response serializer to AFHTTPResponseSerializer and removed the acceptable content types line. Then the response came as NSData and I parsed the NSData response to JSON object for all other APIs. But this API is giving this error after changing the response serializer. Here is the error from error block.
JSON text did not start with array or object and option to allow fragments not set.
Am not getting this why this happening. I have tried to change the header acceptable content type to json and html. But those are not making any difference. I have tried the API in Chrome Postman and it's working absolutely fine. Please suggest something, where am doing wrong.
Set Content-type to application/Json and try
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
i am trying to send json array data to server but it show the result is failed.
so plaese correct me where i did wrong.Here is code what i am using in this:
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [NSString stringWithFormat:#"%#",jsonString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://anaadit.net/caffe/newapp/AddGroupContact.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn==nil) {
NSLog(#"Connection could not be made");
} else {
responseData = [NSMutableData new];
NSLog(#"%#",responseData);
}
and nsurl connection delegate methods calling but the response is showing is nil .
so please check and correct me .Thanks in advance.
Use AFNetworking frame work instead, easy to use and implement.
https://github.com/AFNetworking/AFNetworking
POST request in AFNetworking -
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
manager.requestSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://anaadit.net/caffe/newapp/AddGroupContact.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
To set ant http header field you can use,
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Please contact your webservice developer, he/she may have had some issue
Your question has been answered here: How to send POST and GET request?
Although judging from your comment, the issue isn't with the actual request but rather with the server. You wouldn't have gotten a response if your request code was faulty. You should check that the parameters are corresponding with what the server needs.
You can also check the status code of the request like so:
[(NSHTTPURLResponse*)response statusCode]
I'm having a hard time trying to receive JSON form a NSURLConnection request. Can anybody offer any advice? I can't understand why the JSON does not appear
EDIT: When I append the endpoint /books to the end of the url string I get this JSON response: " json NSDictionary * 0 key/value pairs. " Does this mean that there is nothing in the server?
-(void)makeLibraryRequests
{
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //;]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
[request setHTTPMethod:#"GET"];
// This is actually how jQuery works. If you don't tell it what to do with the result, it uses the Content-type to detect what to do with it.
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//parse data here!!
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (json) {
//NSArray *allBooks = [json objectForKey:#"books"];
//create your MutableArray here
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else{
NSLog(#"error occured %#", jsonError);
NSString *serverResponse = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"\n\nError:\n%#\n\nServer Response:\n%#\n\nCrash:", jsonError.description, serverResponse);
//[NSException raise:#"Invalid Data" format:#"Unable to process web server response."];
}
}];
}
As YiPing pointed out, you must provide the books end point. But you won't have anything there until you first post a book.
NSDictionary *params = #{#"author": #"Diego Torres Milano",
#"categories" : #"android,testing",
#"title": #"Android Application Testing Guide",
#"publisher": #"Packt Publishing",
#"lastCheckedOutBy": #"Joe"};
NSURL *url = [NSURL URLWithString:#"http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxaa56/books/"]; // your id removed for security's sake ... put it back in
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *encodeError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&encodeError];
NSAssert(body, #"JSON encode failed: %#", encodeError);
request.HTTPBody = body;
So, first POST a book using a request like the above, then your original GET (assuming you add the end point) will now return a result.
Add some endpoints to your URL
try this:
http://prolific-interview.herokuapp.com/54bexxxxxxxxxxxxxxxxaa56/books/
I am using AFNetwoking v 2.2.4 as a networking library on iOS. It assumes non http 2xx (http 200 as success ) response as error and throws on error block like this:
NSError *error= nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error:&error];
NSString *connectionString = [NSString stringWithFormat:#"%#%#",SERVER_URL, RESOURCE_URL_USER_SIGNUP];
NSURL *url = [NSURL URLWithString:connectionString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:jsonData];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"response object: %#", (NSDictionary *)responseObject);
[delegate userSignUpCompletedWithResponse:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[delegate userSignUpFailedWithError:error];
NSString *errorBodyMessage = [[error userInfo] objectForKey:#"NSLocalizedRecoverySuggestion"];
NSLog(#"error message: %#", errorBodyMessage);
}];
[operation start];
Here, everything is working as expected when http response is 200. I have a REST API on server side which is written in ROR. For the user sign up, if all fields have valid values then it sends 200 status, but if data are invalid, such as email already taken; In this case server sends 422 status with error message in JSON. I need to trace error message and show it to mobile user but I am unable to get the message object in error block. I have logged entire error but did not find the object returned form the server. How can I get the JSON object while there is non 2xx http response using AFNetworking?
Access the responseObject property of the operation passed into the failure block.
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"JSON: %#", operation.responseObject);
}];