For Android, I've been able to send POST requests in the following way:
HttpClient http = new DefaultHttpClient();
HttpPost request = new HttpPost("https://somewebsite.com");
request.setEntity(new StringEntity(data));
http.execute(request);
However, on iOS I get the following error:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
What is the best way to perform a synchronous POST request using https on iOS?
You can try this function:
-(NSData *)post:(NSString *)postString url:(NSString*)urlString{
//Response data object
NSData *returnData = [[NSData alloc]init];
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
if (debug && response) {
NSLog(#"Response >>>> %#",response);
}
return returnData;
}
And here is how you use it:
NSString *postString = [NSString stringWithFormat:#"param=%#",param];
NSString *urlString = #"https://www.yourapi.com";
NSData *returnData = [self post:postString url:urlString];
Edit:
I found the error code in the source code:
errSSLHostNameMismatch = -9843, /* peer host name mismatch */
The problem should be address on your server.
And here is from the docs:
errSSLHostNameMismatch -9843 The host name you connected with does
not match any of the host names allowed by the certificate. This is
commonly caused by an incorrect value for the kCFStreamSSLPeerName
property within the dictionary associated with the stream’s
kCFStreamPropertySSLSettings key. Available in OS X v10.4 and later.
hope this help
Related
I'm trying to upload a very large JSON string to server using NSMutableURLRequest. If the length of postData is 239741 then it is giving the following response :
{ status code: 404, headers {
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html";
Date = "Fri, 04 Dec 2015 09:12:30 GMT";
Server = "nginx/1.4.6 (Ubuntu)";
"Transfer-Encoding" = Identity;
} }
But if I try to post JSON string to server with postData length of 206044, then data gets successfully uploaded to server.
How can I upload a JSON string of unlimited length to a server?
Complete code given below :
NSString *urlString = [NSString stringWithFormat:#“URL Here”];
NSData *postData = [[NSString stringWithFormat:#"data=%#",postValues] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", (int)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setValue:[NSString stringWithFormat:#"Token %#",AuthToken] forHTTPHeaderField:#"Authorization"];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:50];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error1 = nil;
NSHTTPURLResponse *response=nil;
NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error1];
NSLog(#"response is %#",response);
NSString* responseString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response string is %#",responseString);
if (responseData) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error1];
return json;
}
else
NSLog(#"Error : %#",error1.description);
First of all check your web-service URL.
The 404 or Not Found error message is an HTTP standard response code
indicating that the client was able to communicate with a given
server, but the server could not find what was requested.
You can check your web-service using different plugin available on Google Chrome and Mozila firefox which is listed below.
POSTMAN
REST Client
May this helps lot.
Look up what status 404 means. Google is your friend here. It means the url that you are using doesn't exist on the server. At least that's what the server says.
I am sending some data to my server using POST method. Code is as follows:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"<myServer ip>"]];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSString *stringData = #"Hello";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
I am not receiving the correct data in from the server.
The code for receiving is:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"didFinishLoading Called");
NSString* newStr = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"data received is = %#",newStr);
}
The response I receive is:
<soapenv:Body>
<soapenv:Fault>
<faultcode xmlns:ns1="xml.apache.org/axis/">ns1:Client.NoSOAPAction</…;
<faultstring>no SOAPAction header!</faultstring>
<detail>
You can't just test a SOAP service by sending an arbitrary string. All you are proving is that the URL is pointing to a server which is expecting to receive SOAP messages. You need to look at the server specification and create the appropriate SOAP payload to be sent. This should replace your current content in stringData.
Hi I'm new to iphone development, I'm currently working with a project where I have a screen, in which user should enter their details, like username and password. I googled and find out about NSURLConnection for GET/POST/DELETE. I can GET data by the below codes,
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://************/api/Users"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"Content-
Type"];
NSURLResponse *response;
NSData *GETData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *ResultData = [[NSString alloc] initWithBytes:[GETData bytes] length:[GETData
length] encoding: NSASCIIStringEncoding];
NSLog(#"ResultData: %#", ResultData);
But for POST method, i doesn't get any ideas of , how it functions and how it store record to sql server database, can't understand whether it s storing data or not, i tried the following codes,
username = #"Aravind.k";
password = #"1234/";
email = #"sivaarwin#gmail.com";
NSString *post = [NSString stringWithFormat:#"FirstName=%#&LastName=%#&WorkEmailAddress=%#",
username, password, email];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://*********/api/Users"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"request: %#", request);
NSLog(#"postData: %#", postData);
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:nil];
NSLog(#"POSTReply: %#", POSTReply);
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes]
length:[POSTReply length]
encoding:NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
Same api url for both GET and POST, any suggestions regarding POST and DELETE will be grateful, Thanks in advance.And how we can get notified as the entered data is stored into the server.
First off: not checking for errors automatically leads to down votes ;)
Please edit your code with full error checks!
When using a MIME type application/x-www-form-urlencoded you need to properly encode the parameters.
I would suggest, to create a NSDictionary holding your parameters, e.g.:
NSDictionary* params = #{#"FirstName": firstName, #"LastName": lastName, #"password": password};
and then use the approach described in the following link to get an encoded parameter string suitable for using as a body data for a application/x-www-form-urlencoded message:
How to send multiple parameterts to PHP server in HTTP post
The link above implements a Category and a method dataFormURLEncoded for a NSDictionary which returns an encoded string in a NSData object:
NSData* postData = [params dataFormURLEncoded];
Note: The MIME type application/x-www-form-urlencoded does not have a charset parameter. It will be ignored by the server. You should set the header like below:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Otherwise, your code should work. I would strongly recommend to use the asynchronous version of the convenient method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue *)queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
I've search and try many different solutions but without luck.
I am trying to make a JSON Request to my server, it works for sure because I've tested it in PHP (simple call, it receives string name and string password and check into the database if the user is correct). The request should receive back a JSON with property "success" only (which could be "true" or "false").
Here is my code:
- (void)logonService:(NSString *) name widthArg2:(NSString *) password {
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://46.51.169.145/ios/index.php/user/login/"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
//setting json fields
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//prepare output data
NSString *in1;
NSDictionary *outputData = [NSDictionary dictionaryWithObjectsAndKeys:in1, #"success", nil];
NSError *error = nil;
NSData *jsonOutputData = [NSJSONSerialization dataWithJSONObject:outputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonOutputString = [[NSString alloc] initWithData:jsonOutputData encoding:NSUTF8StringEncoding];
//set json string to body data
NSData *requestInputBodyData = [jsonOutputString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody: requestInputBodyData];
//prepare input data
NSString *input = [NSString stringWithFormat:#"&name=%#&password=%#",name,password];
//Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *inputData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//calculate length of post data
NSString *inputLength = [NSString stringWithFormat:#"%d",[inputData length]];
//Set HTTP header field with length of the post data.
[request setValue:inputLength forHTTPHeaderField:#"Content-Length"];
//encode type
//[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
//add it to http body
[request setHTTPBody:inputData];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn){
NSLog(#"Connection Successful");
}else{
NSLog(#"Connection could not be made");
}
}
The delegate DidReceiveData fires correctly but the result is always NIL:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *jsonResponseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"RESULT1: %#", jsonResponseData);
[_responseData appendData:data];
}
Thank you, hope someone can help me!
thanks a lot for the comments, I finally fix it, and after that I decided to starting using a JSON library --> https://github.com/stig/json-framework/
This is how I finally have the code:
//prepare connection
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#user.php", _urlServer]];
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:#"login" forKey:#"action"];
[data setObject:username forKey:#"username"];
[data setObject:password forKey:#"password"];
//start connection
// Create the request, if there is a connection going on just cancel it.
[_connection cancel];
//initialize new mutable data
NSMutableData *receivedData = [[NSMutableData alloc] init];
_receivedData = receivedData;
//initialize the url which will be fetched
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
//initialize a post data
NSString *dataString = [[NSString alloc] init];
for(id key in data) {
id value = [data objectForKey:key];
//keys string
NSString *newData = [NSString stringWithFormat:#"&%#=%#", key, value];
dataString = [dataString stringByAppendingString: newData];
}
//set request content type we MUST set this value.
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//set post data of request
[request setHTTPBody:[dataString dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
_connection = connection;
//NSLog(#"Sending request with parameters: %#", dataString);
//begin the connection
[_connection start];
And its working like a charm. Next step is to authenticate somehow, right now connection is open to the world.
I am currently connecting my iOS native app to a facebook page in order to post a message to that wall. I can access the wall but for some reason there's no message text set. I asked the user for 'publish_stream' permissions.
Any idea what I'm doing wrong? Here's my code:
NSMutableDictionary *message = [NSDictionary dictionaryWithObjectsAndKeys:#"some text", #"message", #"http://path/to/itunes/", #"link", nil];
NSString *changeJSON = [message JSONRepresentation];
NSLog(#"changeJSON: %#", changeJSON);
NSData *myPostData = [changeJSON dataUsingEncoding:NSUTF8StringEncoding];
NSString *myURL = [NSString stringWithFormat:#"https://graph.facebook.com/pageId/feed?access_token=%#", facebook.accessToken];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [myPostData length] ] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: myPostData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"return string: %#", returnString);
[facebook logout:self];
The string which is encoded to a NSData object is the following:
{"message":"some text","link":"http://path/to/itunes/"}
Thanks and have a nice day :-)
It looks like you're attempting to post JSON to the GraphAPI? If so, you can't post JSON to Facebook, but instead have to use parameters when posting (either query string or HTTP request parameters).
All posting actions are done via HTTP POST with parameters and all responses are done in JSON. You can read more on this via the Graph API reference under publishing.
See: POST Reference.