Post Data to Webservice URL - objective-c

I have problem with my code for posting data to webservice.
Can someone please, tell me where I am going wrong.
I need to post three fields (doctorId-STRING, patientId. STRING, date-STRING) to this address:
http://www.walter-dev.com/doctor/public/setTermin
How to make this right?
NSString *post = [NSString stringWithFormat:#"&id_doktor=%#&id_pacijent=%#&datum=%#",#"iddoktora",#"idpacijenta",#"ovojedatum"];
NSData* postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//You need to send the actual length of your data. Calculate the length of the post string.
NSString *postLength = [NSString stringWithFormat:#”%d”,[postData length]];
//Create URLRequest object and initialize it.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//Set the Url for which your going to send the data to that request
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.walter-dev.com/doctor/public/setTermin"]]];
//set HTTP method (POST)
[request setHTTPMethod:#"POST"];
//Set header field with lenght of the post data
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//I dont understand this line of code
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
//Set httpbody of the urlrequest with string "post"
[request setHTTPBody:postData];
//Initialize object with urlRequest
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Konekcija prema serveru je uspjela");
}
else
{
NSLog(#"NIJE USPJELA ");
}

Related

Checking data sent in http post Request

Is it possible to check the data which I have sent in HTTP POST request, by logging the request in XCode.
Here is my code:
NSString *post = [NSString stringWithFormat:#"Firstname=%#&Lastname=%#&Email=%#",firstName,lastName,emailId];
NSLog(#"%#", post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.abcde.com/xyz/login.aspx"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
**NSLog(#"%#", request );**
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
I am logging the request as shown above in Bold. But here I am able to see only my Url and not any post data.
If it is not possible to see data here where can I see the data sent in http request.
If you want just check what data are you sending then I suggest you to use this awesome tool http://www.charlesproxy.com. It's very simple and powerful.
Just run Charles and do your request via simulator.

post request to server does not send the content of textfields?

I'm trying to send the content of my textfields firstname and lastname with my button sendpost to my php server. Once I run my app and fill my textfields with some random text and press send, I receive an e-mail on my server but there is no content.
(void) sendAction{
NSError *error = nil;
NSString *postparams = [NSString stringWithFormat:#"info=%#_%#",firstname.text,lastname.text];
NSData * postdata = [postparams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postlength= [NSString stringWithFormat:#"%d",[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://faketest.com/test/mail.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postdata];
NSData * rawdata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *rawdatastring =[[NSString alloc]initWithData:rawdata encoding:NSUTF8StringEncoding];
NSLog(#"%#",rawdatastring);
}
I believe it may be because you're using a "Current-Type" header, instead of the usual "Content-Type" header. Try the following and see if it solves the problem:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];

NSURLConnection POSTing JSON data to ASP.Net WebAPI not returning a response

I am currently posting json data using an asynchronous NSURLConnection to a ASP.Net WebAPI resource. The connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: is being called, and the correct amount of data is being written. But the connection:didReceiveResponse:, connection:didReceiveData: or connectionDidFinishLoading: are not being called, but eventually it gives up, and the connection is lost.
I am setting up the connection as follows:
NSURL *url = [[NSURL URLWithString:[Common baseUrl]] URLByAppendingPathComponent:#"api/iCat/wishlists/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.f];
NSString *jsonString = [self generateStrippedJsonForWishlist:wishlist];
NSData *requestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:requestData];
And initiating the connection with:
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Eventually the request will time out with a "The network connection was lost" error message. To me it seems like the app is never completely finished writing the body of the message.
From the api side, the method is never actually being called (break point is not being hit). But if I send the request with no body, then it does.
I have tested the same call using curl, and it is working as expected:
curl -v -i -X POST -H "Content-Type: application/json" -d '{"CreatedBy":"iPad Simulator","ContactName":"Ddd","ContactEmail":"ddd","Products":[{"ProductId":117,"ProductName":"Internal doors - deco","Specification":""}]}' http://SCMOBILE02:1861/api/iCat/wishlists/upload
Try library https://github.com/AFNetworking/AFNetworking while posting json data.
Can you try the following code below ?
-(void) post
{
NSString * a = #"{company_name : \"com\"}";
NSString * URL = #"yourUrl";
NSString *post = [NSString stringWithFormat: #"%#",a];
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:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setTimeoutInterval:20.0];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];
}
In your web api you should have the following class and post method like below
public class company
{
public string company_name { get; set; }
}
// POST api/values
public void Post([FromBody]company value)
{
var t = value;
}

Instagram API responds with code 400 (Bad Request)

I've sent this URL via post:
https://api.instagram.com/v1/users/XXX/relationship?action=unfollow&access_token=YYY
XXX is a valid userid, I've checked that multiple times. The token (YYY) is correct too.
This is the response:
{"meta":{"error_type":"APIInvalidParametersError","code":400,"error_message":"please supply action=approve,ignore,follow,block,unblock,unfollow"}}
I've tried action=follow and action=unfollow. Is it possible, that this is a bug? Where can I report it?
Instagram API Documentation: http://instagram.com/developer/endpoints/relationships/
The problem is that you are not sending the action as postdata. I had the exact problem just yesterday.
The access_token should be sent in the url, but the action=follow should be in the postdata of the request!
NSString *initialURL = [NSString stringWithFormat:#"https://api.instagram.com/v1/users/USER_ID/relationship?access_token=ACCESS TOKEN"];
NSURL *url=[NSURL URLWithString:initialURL];
NSString *key = [NSString stringWithFormat:#"action=follow"];
NSData *mastData = [key dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *mastLength = [NSString stringWithFormat:#"%d",[mastData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:mastLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:mastData];
NSURLConnection *con=[[NSURLConnection alloc]initWithRequest:request delegate:self];
[con start];
Also make sure to use proper scope while authenticating.
Add scope=like+comments+relationships in that authentication URL.

Post data in Objective C using Json

I am trying to post data to a PHP web service.
I am familiar doing this in html using query $.post but I am very much stumped trying this in objective C.
I tried several blogs & questions found on stackoverflow.
I finally came up with the following code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"Email\":\"%#\",\"FirstName\":\"%#\"}",user,fname];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http:myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I also tried:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
My web service creates a new user on post and returns the userID.
Both successfully make the web service call(a new userID is created), however they do not post the data, i.e. a blank user is created every time.
Please tell me if I am missing anything.
Thanks.
My other attempts:
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"myUrl.. "]];
[request setHTTPMethod:#"POST"];
NSString *postString = #"Email=me#test.com&FirstName=Test";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc]
initWithRequest:request delegate:self];
I finally solved the issue:
FInally, figured out what was wrong. I was using http://mypath?params=123 as my url. I did not gig the complete url(never needed it in other languages). But here I needed to give htt://mypath/index.php?params=123
I think you would be better off using the NSJSONSerialization class like this:
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
email, #"Email",
fname, #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postData];
Using a dictionary and then converting it to JSON it's easier than creating it like a string.
Good luck!
[SWIFT 3.0] (update)
let tmp = ["email": email,
"FirstName": fname]
let postData = try? JSONSerialization.data(withJSONObject: tmp, options: .prettyPrinted)
request.httpBody = postData
I have run your code, and server side receive all message.
POST / HTTP/1.1
Host: linux-test
User-Agent: demoTest/1.0 CFNetwork/548.1.4 Darwin/11.3.0
Content-Length: 44
Accept: application/json
Content-Type: application/json
Accept-Language: en
Accept-Encoding: gzip, deflate
Connection: keep-alive
{"Email":"test#test.com","FirstName":"test"}
And follow code, if jsonRequest has Non-ASCII characters, the [jsonRequest length] will be wrong.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
You can use strlen instead.
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:strlen([jsonRequest UTF8String])];
or
[jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
Try this one
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"%#posts", SeverURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"content-type" value:#"application/json"];
[request addRequestHeader:#"User-Agent" value:#"iOS"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
request.delegate=self;
NSString *json=[[self prepareData] JSONRepresentation];//SBJSON lib, convert a dict to json string
[request appendPostData:[NSMutableData dataWithData:[json dataUsingEncoding:NSUTF8StringEncoding]]];
[request startSynchronous];