xml posting in iOS without using frameworks? - ios

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

Related

Objective c post request is not working

I have looked at a lot of posts about http post requests and I still have not been able to find the answer. My problem is that I need to send one string to my work partners website so it can be accessed using a GET request and used for a leader board/
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[req setHTTPMethod:#"POST"];
NSData *postData = [revs dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[req addValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPBody:postData];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something with response data here - convert to JSON, check if error exists, etc....
NSLog(response.description);
// NSLog([[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
}];
[task resume];
But the request never goes to the website, it is called ../distances.txt
Can anyone help?

How to Design the Overlay Menu Above the Home Page?

How to Design the Overlay Instructions Above The View?
I HAD 6 buttons....For Each Button I have To show Overlay For That, Before i click on that Button
Suppose... 1) Click button is there...above the Click Button we need
to show overlay for click on that button Like That...
**
[I Need Like This Overlay menu over the all Buttons][1]
[1]: http://i.stack.imgur.com/dIjRF.jpg
**
Use NSURLSession instead. NSURLConnection is deprecated.
NSString *stringURL = [NSString stringWithFormat:#"%#?term=%#", BASE_URL, _inputText.text];
NSURL *URL = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:yourData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// Do your stuff here
}];
why not use alamofire---
NSDictionary *parameters = #{
#"email": #"myemail1#mailinator.com",
#"password": #"123456789",
#"accountnumber": #"LiM6N5gBBmqdlQBJGkqcP0h4OKwGbnzoWFcgTG3Z",
#"ifcscode": #"ABC"
};
NetworkHandler *networHandler = [NetworkHandler sharedInstance];
[networHandler composeRequestWithMethod:#"http://example.com/enpoint.json"
paramas: parameters
onComplition:^(BOOL success, NSDictionary *response){
if (success) { //handle success response
[self handleLoginResponse:response];
}
else{
ProgressIndicator *pi = [ProgressIndicator sharedInstance];
[pi hideProgressIndicator];
}
}];
you can use postman to check your api
Pass this two variables of FirstViewController to SecondViewController and then try to put below code in place of your code.
Below is code to POST data using NSURLSession.
I hope this works for you.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"Name=%#&Email=%#&A/CName=%#&A/CNumber=%#&IFSCCode=%#&TypeOfAccount=%#",name,email,acName,acNumber,ifscCode,typeOfAccount];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSMutableDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}] resume];
}
Send Parameter to web service using POST method
Below is code to POST data to web service using NSURLConnection.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"email=%#&name=%#",textEmail.text,textName.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}

NSURLSession POST is not working and returning 500 status code in iphone

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

Objective c post request not sending the data

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];

How to make a PUT request in NSURLSession?

I want to make a PUT request to a URL, but when the output shows status code as 405, which means the request to the URL is something other than put.
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSURL * url = [NSURL URLWithString:#"http://httpbin.org/put"];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:url];
NSData *postbody = [#"name=testname&suggestion=testing123" dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
request.HTTPMethod = #"PUT";
[request setHTTPBody:postbody];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
[request setHTTPBody:data];
NSLog(#"Response = %#",response);
}
}];
[dataTask resume];
Can someone point out where i am going wrong, i have been reading a lot about this issue since the last couple of hours, but i am not able to figure it out. Kindly do not mark this as duplicate since the previous op did not add body which is not the case with my code. Also the URL mentioned accepts any data as body, so i guess what i set the data to is irrelevant.
EDIT (ANSWER):
After banging my head from yesterday, one of my senior helped me solve the issue, hope this will help someone. The data task needs to be supplied with the request object and not with the URL, this was the reason it always showed 'GET' in Charles web debugging tool. The code should be as follows:
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// code
}];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"PUT";

Resources