I am tried to Post String value to Sql Server.like this
NSString *post =[NSString stringWithFormat:#"?&name=%#&password=%#&pin=%#&email=%#&phone=%#&address=%#&city=%#&status=%#",
name, password ,pin ,email ,phone,address,city,status];
NSLog(#"post%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://202.65.154.108:8080/SaveDollar/rest/deals/add"]]];
NSLog(#"getData%#",request);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSLog(#"getData%#",request);
con3 = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(con3)
{ webData3=[NSMutableData data];
NSLog(#"Connection successful");
NSLog(#"GOOD Day My data %#",webData3);
}
else
{
NSLog(#"connection could not be made");
}
I tried like this connection successful.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *responseText = [[NSString alloc] initWithData:webData3 encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);}
But get Response like this HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
I am not understand What my mistake so Please give me any idea,and Please tell me What wrong in my code.
Thanks in Advanced .
5xx Server Error
HTTP 500 Internal Server Error
A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. Source of this Wikipedia : - List of HTTP status codes and w3.org Status codes
So need to check on server side. It's not your issue.
HTTP 500 Internal error (or) internal server error
It is meant that the error may be on several reasons
- The fault may be from server side i.e Json
- The fault may be from your side in which the parameters which you are sending may be in correct format which is expected from server
- The fault may be coding side which leads to crash
Related
I am currently building an app in Xcode using Objective C and I need to post two text variables and an image. As of right now, I can only post the two text variables but I would like to send an image from my UIImageView to the server by using the FILES variable from the HTTP POST Request.
Here is the working code for my POST Request:
- (IBAction)posttoserver:(id)sender {
NSString *post = [NSString stringWithFormat:#"process=writepost&auth_token=%#&app_id=0&posttextarea=%#&url=%#", authkey, encodedmessage, encodedlink];
NSData *data = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength = [NSString stringWithFormat:#"%lu", (unsigned long)[data length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"my-server.com"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
NSLog(#"Connection!");
}
else {
NSLog(#"No Connection");
}
[_posttext resignFirstResponder];
[_postlink resignFirstResponder];
}
Continued:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Post Response: %#", response);
if ([response isEqualToString:#"success"]) {
// NSLog Success
}
else {
// Something is wrong
}
}
As you can see, I am posting the user editable text as well as a link for the post. Also, you might notice that I am attaching "process=writepost&auth_token=%#&app_id=0" and those are just needed for the server to recognize who is posting and what process is being sent to the specific URL.
Now, I would like to attach an image to the POST request by adding an image from the UIImageView. How would I attach it into the FILES variable for the POST request?
Any help would be gladly appreciated.
Thanks in advance,
Kyle
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 have search around and can't quite find the right answer to this, but I have this code which posts data to my web server, and I am trying to get the HTTP response, but the response keeps returning (null). I can confirm that the connection is successful because the if statement (see below) executes the appropriate code.
Here is my code:
-(void)submitAction{
NSString *post = [NSString stringWithFormat:#"&var1=%#&var2=%#&var3=%#&var4=%#",
_var1, _var2, _var3, _var4];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://my-web-server.com/path-to-web-service/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
NSURLResponse *response;
NSLog(#"%#", response); // Always returns null :(
if(conn){
NSLog(#"Connection Successful."); // Connection is successful in my tests.
}else{
NSLog(#"Connection could not be made");
}
}
Here is the NSURLConnectionDelegate delegate implemented in my .h file:
#interface AddTaskViewController : UIViewController <UITextFieldDelegate, UIPickerViewDelegate, NSURLConnectionDelegate>
Can anyone see what I am doing wrong here? The server should return a JSON string, (and it does when I test the web service via my browser) but the NSURLResponse is constantly null.
Thanks,
Peter
Using initWithRequest:delegate: of NSURLConnection starts an asynchronous download, so it returns immediately and executes straight away.
response is always nil because you just defined it and then logged it without ever setting it to anything. That needs to be done in the connection:didReceiveResponse: delegate method.
Where you do if(conn){, the conn existing doesn't mean the connection was successful, it just means that the connection could be created (basically, you didn't supply an invalid request). You don't know whether it's going to work yet.
Implement the delegate methods from NSURLConnectionDelegate_Protocol (and NSURLConnectionDataDelegate) to get access to the response and downloaded data (when it becomes available).
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