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 ");
}
I want to create an iPhone application to send data to a Rest API service. If the data is a string defined as geoX#35#geoY#65 which NSS method shall i use. Was thinking of NSString and NSMutablerequest to make my request and define my string but this isn't working atm.Also i am using NSURLconnection to establish a connection with the server(maybe that's faulty too). Anyone that can help ?
Thanks in advance.
Your connection data is using special characters and if you try to do this with GET method of NSURLConnection. It will Shows connection error. For this You have to use POST method like :
NSData *body = nil;
NSString *contentType = #"text/html; charset=utf-8";
NSURL *finalURL = #"YOUR URL WITH the ?input=";
NSString *yourString = #"geoX#35#geoY#65";
contentType = #"application/x-www-form-urlencoded; charset=utf-8";
body = [[NSString stringWithFormat:#"%#", yourString] dataUsingEncoding:NSUTF8StringEncoding];
if (nil==finalURL) {
finalURL = url;
}
NSMutableDictionary* headers = [[[NSMutableDictionary alloc] init] autorelease];
[headers setValue:contentType forKey:#"Content-Type"];
[headers setValue:mimeType forKey:#"Accept"];
[headers setValue:#"no-cache" forKey:#"Cache-Control"];
[headers setValue:#"no-cache" forKey:#"Pragma"];
[headers setValue:#"close" forKey:#"Connection"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:finalURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:body];
self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
What would be the reason for getting Invalid Request when we are posting an URL to server in iOS SDK. the URL what i am sending is correct and the data what I'm posting is also correct.
I tried in RestClient also even though I'm getting same error Invalid Request in that also.
Can any one help me what would be the reason for it.
Thanks in advance.
- (NSURLConnection *) executeAsyncHttpPost :(NSString *) baseURL :(NSString *) method
:(id) jsonParams :(int)callerTag
{
NSLog(#"jsonParams: %#", jsonParams);
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
NSLog(#"urlstr: %#", urlstr);
NSString *postLength = [NSString stringWithFormat:#"%d", [jsonParams length]];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [[NSData alloc] initWithData:[jsonParams dataUsingEncoding:NSASCIIStringEncoding]];
NSString* myString;
myString = [[NSString alloc] initWithData:requestData encoding:NSASCIIStringEncoding];
NSLog(#"myString: %#", myString);
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
self.tag = callerTag;
return [super initWithRequest:request delegate:delegateResponder];
}
The JSON you are posting might be invalid. Please validate it using this. There should be no character outside the { }.
Just post the following string instead of the current JSON
EDIT:
{"jsonRequest" :{"methodName":"CheckUserExist","username":"giriraj.vyas#dotsquares.com","password":"233444"}}
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;
}
I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST request to a website. The apple example on the support site is rather complicated showing a picture upload.. mine should be simpler.. I just want to post 2 lines of text..
Anyone have any good examples?
Alex
This is what I recently used, and it worked fine for me:
NSString *post = #"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = #"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:#"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = #"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
ASIHTTPRequest makes network communication really easy
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addPostValue:#"Ben" forKey:#"names"];
[request addPostValue:#"George" forKey:#"names"];
[request addFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photos"];
[request addData:imageData withFileName:#"george.jpg" andContentType:#"image/jpeg" forKey:#"photos"];
You can do using two options:
Using NSURLConnection:
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyrambody",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
// Connection
NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
Using NSURLSession
- (void)sendRequest:(id)sender
{
/* Configure session, choose between:
* defaultSessionConfiguration
* ephemeralSessionConfiguration
* backgroundSessionConfigurationWithIdentifier:
And set session-wide properties, such as: HTTPAdditionalHeaders,
HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
*/
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
/* Create session, and optionally set a NSURLSessionDelegate. */
NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];
/* Create the Request:
Token Duplicate (POST http://www.example.com/path)
*/
NSURL* URL = [NSURL URLWithString:#"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = #"POST";
// Form URL-Encoded Body
NSDictionary* bodyParameters = #{
#"username": #"reallyram",
#"password": #"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];
/* Start a new Task */
NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Success
NSLog(#"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
}
else {
// Failure
NSLog(#"URL Session Task Failed: %#", [error localizedDescription]);
}
}];
[task resume];
}
/*
* Utils: Add this section before your class implementation
*/
/**
This creates a new query parameters string from the given NSDictionary. For
example, if the input is #{#"day":#"Tuesday", #"month":#"January"}, the output
string will be #"day=Tuesday&month=January".
#param queryParameters The input dictionary.
#return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
NSMutableArray* parts = [NSMutableArray array];
[queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
NSString *part = [NSString stringWithFormat: #"%#=%#",
[key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
[value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
];
[parts addObject:part];
}];
return [parts componentsJoinedByString: #"&"];
}
/**
Creates a new URL by adding the given query parameters.
#param URL The input URL.
#param queryParameters The query parameter dictionary to add.
#return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
NSString* URLString = [NSString stringWithFormat:#"%#?%#",
[URL absoluteString],
NSStringFromQueryParameters(queryParameters)
];
return [NSURL URLWithString:URLString];
}
I am a beginner in iPhone apps and I still have an issue although I followed the above advices. It looks like POST variables are not received by my server - not sure if it comes from php or objective-c code ...
the objective-c part (coded following Chris' protocol methodo)
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://example.php"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [NSString stringWithFormat:#"user_name=%#&password=%#", self.userNameField.text , self.passwordTextField.text];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(#"Response: %#",[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]);
Below the php part :
if (isset($_POST['user_name'],$_POST['password']))
{
// Create connection
$con2=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// retrieve POST vars
$username = $_POST['user_name'];
$password = $_POST['password'];
$sql = "INSERT INTO myTable (user_name, password) VALUES ('$username', '$password')";
$retval = mysqli_query( $sql, $con2 );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysqli_close($con2);
}
}
else
{
echo "No data input in php";
}
I have been stuck the last days on this one.
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:#"name" forKey:#"email"];
[contentDictionary setValue:#"name" forKey:#"username"];
[contentDictionary setValue:#"name" forKey:#"password"];
[contentDictionary setValue:#"name" forKey:#"firstName"];
[contentDictionary setValue:#"name" forKey:#"lastName"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
NSString *urlString = [NSString stringWithFormat:#"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:#"moinsam" password:#"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];
Thanks a lot it worked , please note I did a typo in php as it should be mysqli_query( $con2, $sql )
Here i'm adding sample code for http post print response and parsing as JSON if possible, it will handle everything async so your GUI will be refreshing just fine and will not freeze at all - which is important to notice.
//POST DATA
NSString *theBody = [NSString stringWithFormat:#"parameter=%#",YOUR_VAR_HERE];
NSData *bodyData = [theBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//URL CONFIG
NSString *serverURL = #"https://your-website-here.com";
NSString *downloadUrl = [NSString stringWithFormat:#"%#/your-friendly-url-here/json",serverURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]];
//POST DATA SETUP
[request setHTTPMethod:#"POST"];
[request setHTTPBody:bodyData];
//DEBUG MESSAGE
NSLog(#"Trying to call ws %#",downloadUrl);
//EXEC CALL
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"Download Error:%#",error.description);
}
if (data) {
//
// THIS CODE IS FOR PRINTING THE RESPONSE
//
NSString *returnString = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString);
//PARSE JSON RESPONSE
NSDictionary *json_response = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
if ( json_response ) {
if ( [json_response isKindOfClass:[NSDictionary class]] ) {
// do dictionary things
for ( NSString *key in [json_response allKeys] ) {
NSLog(#"%#: %#", key, json_response[key]);
}
}
else if ( [json_response isKindOfClass:[NSArray class]] ) {
NSLog(#"%#",json_response);
}
}
else {
NSLog(#"Error serializing JSON: %#", error);
NSLog(#"RAW RESPONSE: %#",data);
NSString *returnString2 = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
NSLog(#"Response:%#",returnString2);
}
}
}];
Hope this helps!