HTTPost setEntity equivalent in iOS - ios

I have an android application which communicates to the server through HTTP Post.
Here is the code and url_select is "http://example.com/Padua/rest/messages/messagetodelete"
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost post = new HttpPost(url_select);
post.setEntity(new ByteArrayEntity(message.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);
This works well and I am able to get the message in the server. But when I try implementing this in iphone I am struck. I am not sure how to accomplish this. In Exact, the setentity part in NSMutalbleURLRequest
Below is the code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[NSURL URLWithString:#"http://example.com/Padua/rest/messages/messagetodelete"];
[request setURL:[NSURL URLWithString:#"http://example.com/Padua/rest/messages/messagetodelete"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//This is where I am getting confused. How to pass the messageid to the URL??
[request setHTTPBody:messageid];
//This is where I am getting confused
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:messageid
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Can any one please help me. I need to pass on the messageid in the URL itself in iOS as in Android.
Thanks and if you need any addtional info, I will provide you

Related

Getting Request Token From Dropbox OAuth "Invalid OAuth Request"

I'm trying to get a response data from dropbox oauth as described here
Now i dont know why it keeps saying {"error": "Invalid OAuth request."}
Here is a my complete code for requesting token:
-(void)requestTokenSecret
{
NSString* oauthVersion=#"1";
NSString* oauth_signature_method=#"PLAINTEXT";
NSString* postHeader = [NSString stringWithFormat: #"Authorization: OAuth oauth_version=\"%#\", oauth_signature_method=\"%#\", oauth_consumer_key=\"%#\", oauth_signature=\"%#&\"",oauthVersion,oauth_signature_method,APP_KEY,APP_SECRET];
NSLog(#"URL HEADER: %#",postHeader);
NSData* postHeaderData = [postHeader dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest* request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"https://api.dropbox.com/1/oauth/request_token"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d",[postHeaderData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postHeaderData];
NSURLConnection* conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
if(conn)
{
NSLog(#"Connected");
}
else
NSLog(#"Connected");
}
It looks like you're putting "Authorization: OAuth ..." in the body of the POST request instead of putting "OAuth ..." in the Authorization header.
Give this code a try instead (untested, sorry):
NSString* oauthVersion=#"1";
NSString* oauth_signature_method=#"PLAINTEXT";
NSString* authorizationHeader = [NSString stringWithFormat: #"OAuth oauth_version=\"%#\", oauth_signature_method=\"%#\", oauth_consumer_key=\"%#\", oauth_signature=\"%#&\"",oauthVersion,oauth_signature_method,APP_KEY,APP_SECRET];
NSMutableURLRequest* request= [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"https://api.dropbox.com/1/oauth/request_token"]];
[request setHTTPMethod:#"POST"];
[request setValue:authorizationHeader forHTTPHeaderField:#"Authorization"];
NSURLConnection* conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
Also, I would strongly suggest using OAuth 2 instead of OAuth 1. It's considerably simpler.

Posting to a Google Forms form using NSURLRequest

I am trying to post a string to a Google Form using NSURLRequest. The method seems to be getting called, but the post to the Google Form doesn't appear. This is the code I am using:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
if (connection){
NSLog(#"Connecting...");
}
I created this form solely for testing purposes. "Connecting..." gets logged, so I know the connection is being made, but the string does not appear in the Google Forms Spreadsheet. Am I doing something wrong? Any help would be greatly appreciated.
This piece of code only checks if connection is not nil
if (connection){
NSLog(#"Connecting...");
}
is equivalent to
if (connection != nil){
NSLog(#"Connecting...");
}
As such, it has nothing to do with an actual connection to the URL.
The method initWithRequest:(NSURLRequest *)request delegate:(id)delegate which you are using will perform the request immediately. This means that you have to perform the operations in another order if you want your params to work:
NSURL *requestURL = [NSURL URLWithString:#"https://docs.google.com/forms/d/1T9M6B_k4tiQcSPP5iS2jyU7DCkoRC1jFVql_eQDy9ek/formResponse"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"entry.757751040=Test sent from iOS App";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Along with this, consider implementing NSURLConnectionDelegate.

NSURLRequest not posting values to a Codeigniter API

Good day,
I am trying to use a Codeigniter based API to connect with iOS and using NSURLRequest.
The API is in debugMode and for now it returns the same key value pair as json as the one that you are posting. I have tried posting the values to the link through postman and it works correctly, however when I post it through my iOS application, the json response is received but the array that should contain the post values is empty.
Here is the iOS Code snippet :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSString * params = #"authkey=waris";
NSData * postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
This is the response when I post the same parameters through postman ( A RESTFUL Client for Chrome )
{
"status": "1",
"data": {
"authkey": "warisali"
}
}
However when I query the same API from the above iOS Code I am getting this :
{
data = 0;
status = 1;
}
Any help on the matter will be highly appreciated!
I had same issue (not with CodeIgniter but with Ruby ...)
Try something like this, solved my problem.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BASEURL,service]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSDictionary *paramDict = #{#"authkey": #"waris"};
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:paramDict options:NSJSONWritingPrettyPrinted error:&error];
if (error)
{
NSLog(#"error while creating data %#", error);
return;
}
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];;
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSLog(#"Posting : '%#' to %#",params,url);
[connection start];
I ended up using the ASIHttpRequest + SBJson combo and that worked like Charm!
After adding the ASIHttpRequest core classes and SBJson Classes to parse the JSON, I was able to achieve what I wanted !
The problem is that because of the way you're creating the connection, it will start immediately, before you've finished configuring the request. Thus, you're creating a mutable request, creating and starting the connection, then attempting to modify the request and then trying to start the request a second time.
You can fix that by changing the line that says:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
To say:
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
Or, easier, just move the original instantiation of the NSURLConnection (without the startImmediately:NO) after you've finished configuring your request, and then eliminate the [connection start] line altogether.

How to make a PUT HTTP request in ios sdk?

In my application I need to make a PUT type request. I have followed the below steps
NSString *path = #"http://hostname/api/Account/VerifyUser?applicationToken=72B648C6-B2B7-45ED-BA23-2E8AAA187D2C&emailID=xxx#gmail.com&password=aaaaa";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:path]];
[request setHTTPMethod:#"PUT"];
[request setValue:[NSString stringWithFormat:#"%d", string.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[string dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
For POST and GET I am getting correct output.
I have searched a lot but i am not getting any solution.Please suggest me any possible solution .
Thanks in advance
Try this
For xml request body
Set [request setValue:#"application/x-www-form-urlencoded;charset=utf-8;application/form-data" forHTTPHeaderField:#"Content-Type"];
OR
For json request body
Set [request setValue:#"application/x-www-form-urlencoded;charset=utf-8;application/json" forHTTPHeaderField:#"Content-Type"];

Cannot get correct return message when consuming WCF web-service via NSURLConnection

I have a WCF web-service. If I just put the URL into the browser, I will get the error message: Forbidden. But if I post data through Fetcher(a HTTP Simulator in OS X), I can get the correct return value.
Now, I tried to use NSURLConnection to post data to the web-service and fetch the return value.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:postURL];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse * response = nil;
NSError * error = [[NSError alloc] init];
receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * receivedStr = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
But all I get is just the html code of the error page I can see from the browser(that forbidden message).
Please help me figure it out. Thanks in advance.
EDIT:
I set up a PHP server and try to do the same thing. I works perfectly. Therefore, I highly doubt it is the WCF problem. Anyone has some good ideas?
if you use generated .svc service you need to :
change
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
to
[request addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-type"];
also you need to SOAPAction field according to operation you request
What is you postData?

Resources