I know this question was asked before. And my code is basically utilizing that and some other post here. However I am receiving an error where the page is not found in the response data.
-(void)sendToForm{
whereString = whereField.text;
nameString=name.text;
phoneString=phone.text;
emailString=email.text;
dateChoice = dateLabel.text;
serviceChoice = whatLabel.text;
//initialize new mutable data ***I DONT SEE WHAT THE POINT OF THIS IS
NSMutableData *data = [[NSMutableData alloc] init];
//THIS GIVES me an error, received data is not defined anywhere
// self.receivedData = data;
//initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:#"https://docs.google.com/forms/d/1jeyxQYlgIUylhXnZZEcy6BC2dx_2AUB3qSNuCqFHUDU/viewform"];
//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];
//set http method
[request setHTTPMethod:#"POST"];
//initialize a post data
NSString *postData = [NSString stringWithFormat:#"entry.1550955212=%#&entry.935955213=%#&entry.1547576233=%#&entry.202631922=%#&entry.1387567225=%#&entry.1031369018",serviceChoice,dateChoice,whereString,emailString,phoneString,nameString]; //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:[postData dataUsingEncoding:NSUTF8StringEncoding]];
//initialize a connection from request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//start the connection
[connection start];
}
I have some functions checking the connection and response and they all work. but in the response data it returns as Page Not Found
Needed to be formResponse instead of viewForm
Related
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.
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.
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
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.
I've been reading over code samples and posts for days but I haven't found a definitive way to post JSON data from my Core Data objects to a RESTful web service. There's a TON of documentation about pulling the JSON from a web service but not so much about sending stuff back. Can anyone point me to a good example or post some code on how to do it? I'm using Core Data and I have the object I want to send back mapped to a Dictionary but I'm missing the code to send it to the service.
EDIT:
I ended up with the code below which looks right and runs without errors, but I get 0 bytes of data returned and my webservice doesn't seem to be receiving the request. The JSON data looks good, the URL is correct, and I can hit the webservice and get JSON data back from it. The NSURLConnection delegate methods also fire as expected.
Is there anything I'm missing below?
- (void)SubmitSystems
{
NSFetchRequest * allSystems = [[NSFetchRequest alloc] init];
[allSystems setEntity:[NSEntityDescription entityForName:#"System" inManagedObjectContext:self.managedObjectContext]];
NSError * error = nil;
NSArray * systems = [self.managedObjectContext executeFetchRequest:allSystems error:&error];
//error handling goes here
//for (NSManagedObject * system in systems) {
NSManagedObject *system = systems[2];
NSString *entityString = #"System";
NSString * serverString = [NSString stringWithFormat:#"%#%#", kWebServiceAddress, entityString];
NSURL *url = [NSURL URLWithString:serverString];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:[self jsonSystemDictionary:(System *)system] options:kNilOptions error:&error];
//NSLog([[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]); //debug only
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval: 30.f];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//}
}
You're going to need to NSMutableURLRequest. Using this, you can use setHTTPMethod and pass it the #"POST" string, and then use the attributes of your NSManagedObject to populate the URL, HTTPBody and/or HTTPHeader as needed.