I am facing a problem in making a POST request to a .net webservice method.
I have made a lot of post request but i just don't seem to get the problem i am facing here
The request is made successfully with the help of Rest client
But it always gives me a 400 error
I am using AFNetworking to make the post request
Please find the code below if something is wrong
NSURL *url=[NSURL URLWithString:#"http://WebService.svc"];
NSMutableDictionary *params=[NSMutableDictionary dictionary];
[params setValue:#"cabbage123" forKey:#""];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient postPath:[NSString stringWithFormat:#"Users/%#",userId] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
And i get a html response with this error
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest http://WebService.svc/Users/userid>, NSErrorFailingURLKey=http://WebService.svc/Users/userid, NSLocalizedDescription=Expected status code in (200-299), got 400, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7ba6df0>}
I think there is some problem with AfNetworking for WCF web-services.
Ultimately i could connect and use the web-service by using the standard NSURLConnection class. Though i am facing the same problem for PUT request now.
Have you tried to setup AFNetworking to allow invalid certificates?
httpClient.allowsInvalidSSLCertificate = YES;
of if you want to use operations.
AFSecurityPolicy *sec=[[AFSecurityPolicy alloc] init];
[sec setAllowInvalidCertificates:YES];
operation.securityPolicy=sec;
Related
I am very new to iOS. I am trying to send data through post method to PHP. In PHP it can't take data like $_POST['data'], but it takes $_GET['data']. My iOS code is as follows.
NSString *strURL = [NSString stringWithFormat:#"http://example.com/app_respond_to_job?emp_id=%#&job_code=%#&status=Worker-Accepted&comment=%#",SaveID2,txtJobcode1,alertTextField.text];
NSURL *apiURL = [NSURL URLWithString:strURL];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:apiURL];
[urlRequest setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
_receivedData = [[NSMutableData alloc] init];
[connection start];
NSLog(#"URL---%#",strURL);
Can someone explain why is that, it will be very helpful.
Please Download this file https://www.dropbox.com/s/tggf5rru7l3n53m/AFNetworking.zip?dl=0
And import file in your project
Define in #import "AFHTTPRequestOperationManager.h"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"Your Url"]];
NSDictionary *parameters = #{#"emp_id":SaveID2,#"job_code":txtJobcode1.text,#"status":alertTextField.text};
AFHTTPRequestOperation *op = [manager POST:#"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[responseObject valueForKey: #"data"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
because you send your data via query string in url
i think it will work if you try to pass data in your request's body:[urlRequest setHTTPBody:...]
POST parameters come from the request body, not from the URL string. You'll need to:
Call setHTTPBody on the request and provide the URL-encoded string (sans question mark, IIRC) as the body data
Call setValue:forHTTPHeaderField: to set the Content-Type to application/x-www-form-urlencoded
Either remove the call to [connection start] or use initWithRequest:delegate:startImmediately: so that you aren't starting the connection twice.
That last one is kind of important. You can get strange results if you try to start a connection twice. :-)
I have to make a post request using AFNetworking library with following request parameters
{
"method":"validate",
"name":{
"firstname":"john",
"lastname":"doe"
}
}
How to make this request using latest version of AFNetworking v3 library?
I used the following code and it doesn't work
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSDictionary *parameters = #{\"method\":\"validate\",\"name\":{\"firstname\":\"john\",\"lastname\":\"doe\"}};
[manager POST:#"http://myUrl.." parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",[responseObject description]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
}];
Im getting the following error,
2016-02-13 11:04:54.085 SlideOutMenu[3698:50453] nulllllll
2016-02-13 11:04:55.794 SlideOutMenu[3698:50453] Failure Request failed: internal server error (500)
2016-02-13 11:04:55.795 SlideOutMenu[3698:50453] (null)
As you've already applied [manager setRequestSerializer:[AFJSONRequestSerializer serializer]] no need to convert dictionary to JSON again.
simply pass dictionary as a parameters, it will work.
NSDictionary *name = #{#"firstname": #"john", #"lastname": #"doe"};
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:#"validate" forKey:#"method"];
[parameters setObject:name forKey:#"name"];
Also no need to initialise NSURLSessionConfiguration with defaultSessionConfiguration, AFNetworking will automatically initialise that. Simply use [AFHTTPSessionManager manager].
Your code is fine.Connect with your server guy.
code 500 is server side error.
check out this link for response code detail
http://www.restapitutorial.com/httpstatuscodes.html
I am primarily an android developer and really new to IOS. I am using AFNetworking 1.0 since I am working with an existing source and I am sending a standard http Post request and returning the data like so:
//Sending the post request and getting the result
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://testsite.org/mobile_app"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://testsite.org/mobile_app/studentregister.php"
parameters:#{#"username":username, #"displayname":displayname, #"password":password, #"passwordc":passwordc, #"email":email, #"teacherCode":teacherCode}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
the response should contain the JSON data which looks like this according to burp suit:
{"userCharLimit":"Your username must be between 5 and 25 characters in length"}
{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}
{"passLimit":"Your password must be between 8 and 50 characters in length"}
{"emailInvalid":"Not a valid email address"}
{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.
How can I get those JSON values? I have seen a lot of AFNetworking 2.0 JSON examples and sending JSON Post request but I can seem to find much for version 1.0 let alone getting the values form a standard post request.
Any ideas or resources?
All you should need is to change your code to register a AFJSONRequestOperation instead of AFHTTPRequestOperation.
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
Then you can use this method on AFHTTPClent to create the operation which will actually be of type AFJSONRequestOperation.
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];
I'm attempting to make an iphone app that will interact with a particular JIRA server. I've got the following code to log in:
NSURL *url = [[NSURL alloc] initWithString:#"https://mycompany.atlassian.net/rest/auth/latest/session/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"{\"username\":\"%#\",\"password\":\"%#\"}", username, password];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept" ];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR: %#", error);
}
];
[operation start];
But it's giving me the following error having to do with Content-Type:
ERROR: Error Domain=AFNetworkingErrorDomain Code=-1011
"Request failed: unsupported media type (415)"
UserInfo=0x8cd6540
{
NSErrorFailingURLKey=https://mycompany.atlassian.net/rest/auth/latest/session/,
NSLocalizedDescription=Request failed: unsupported media type (415),
NSUnderlyingError=0x8c72e70
"Request failed: unacceptable content-type: text/html",
I'm not sure what the problem is. I found this question, which I thought might be a similar problem, but the answers say to either use the AFJSONRequestOperation class (which I can't because I'm using AFNetworking version 2, which doesn't have that class), or to fix it on the server side (which I also can't for obvious reasons).
What can I fix this error when I can't fix the server side and I can't use AFJSONRequestOperation?
If using AFNetworking 2.0, you can use the POST method, which simplifies this a bit:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"username":username, #"password":password};
[manager POST:#"https://mycompany.atlassian.net/rest/auth/latest/session/" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This does the creation of the request, setting its Content-Type according to the requestSerializer setting, and encodes the JSON for you. One of the advantages of AFNetworking is that you can get out of the weeds of constructing and configuring NSURLRequest objects manually.
By the way, the "Request failed: unacceptable content-type: text/html" error means that regardless of what you were expecting to receive (e.g. JSON), you received HTML response. This is very common: Many server errors (e.g. the server informing you that the request was malformed, etc.) generate HTML error messages. If you want to see that HTML, in your failure block, simply log the operation.responseString.
It turns out the problem is that this one line:
[request setValue:#"application/json" forHTTPHeaderField:#"Accept" ];
Should be
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type" ];
The error is now solved. (Edit: I should have both, see CouchDeveloper's comment.)
EDIT
Rob's solution is better, so I'm going with it. I had actually tried a similar solution to what he shows, but where he had the line,
manager.requestSerializer = [AFJSONRequestSerializer serializer];
I had the line:
[manager.requestSerializer
setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
...which didn't work. Kudos to Rob for getting it to work!
I had the same problem in AFNetworking 2.0 and the solution was that I had to make sure I set the AFHTTPRequestSerializer type (In case your request is JSON) the it should be like this.
AFHTTPSessionManager *myHTTPManager = ...
[myManager setRequestSerializer:[AFJSONRequestSerializer serializer]];
You have to set both AFHTTPResponseSerializer and AFHTTPRequestSerializer
if you are using default written class AFAppDotNetAPIClient and you face this error. Must add responseSerializer. see your shared method should look like -
+ (instancetype)sharedClient {
static AFAppDotNetAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[AFAppDotNetAPIClient alloc] initWithBaseURL:[NSURL URLWithString:AFAppDotNetAPIBaseURLString]];
_sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
_sharedClient.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return _sharedClient;}
Use this line of code.
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
I'm trying to connect using AFNetworking to API that is under https address. I keep getting 404 since the old app, based on ASIHTTPRequest is able to connect.
Do I have to implement certificate file into app somehow? What else should be provided?
Basically you have to add nothing, you only need to add http basic auth credentials if needed. This is how i usually connect to a https api with http basic auth.
//Base URL
NSURL *requestPasswordURL = [NSURL URLWithString:BASEURL];
//Http client with server credentials
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:requestURL];
[httpClient setAuthorizationHeaderWithUsername:#"user" password:#"password"];
//Set request parameters for example email
NSDictionary *params = #{#"email": email};
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:API_REQUEST parameters:params];
request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
//Prepare request
AFHTTPRequestOperation *request = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[requestPasswordOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Your code
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//Your Code
}];
//call start on your request operation
[request start];