I am trying to make a HTTP request in this way:
NSString *urlString = [NSString stringWithFormat:#"https://api.dropbox.com/1/oauth/request_token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
//set headers
NSString *contentType = [NSString stringWithFormat:#"text/xml"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
oauth_version="1.0"
oauth_signature_method="PLAINTEXT"
oauth_consumer_key="<app-key>"
oauth_signature="<app-secret>&"
//create the body
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:#"<xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"<yourcode/>"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:#"</xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
//post
[request setHTTPBody:postBody];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
NSLog(#"Response: %#", result);
//here you get the response
}
I am trying to make the request with these headers:
Authorization: OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_signature="<app-secret>&"
But I can't understand how to. PLease help!!
The authorization in your case is just a HTTP header. So it's:
[request addValue:#"OAuth oauth_version=\"1.0\", oauth_signature_method=\"PLAINTEXT\", oauth_consumer_key=\"<app-key>\", oauth_signature=\"<app-secret>&\"" forHTTPHeaderField: #"Authorization"];
Or:
NSString* oauth_version=#"1.0";
NSString* oauth_signature_method=#"PLAINTEXT";
NSString* oauth_consumer_key=#"<app-key>";
NSString* oauth_signature=#"<app-secret>&";
NSString* authHeader = [NSString stringWithFormat: #"OAuth oauth_version=\"%#\", oauth_signature_method=\"%#\", oauth_consumer_key=\"%#\", oauth_signature=\"%#\"",
oauth_version, oauth_signature_method, oauth_consumer_key, oauth_signature];
Try commenting all this
//NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
//NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"Response Code: %d", [urlResponse statusCode]);
//if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
// NSLog(#"Response: %#", result);
//here you get the response
//}
and use this instead of all above
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
Implement these delegate functions
Note - self.data is NSMUtableData object declared as data in header.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.data setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
[self.data appendData:d];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error", #"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", #"")
otherButtonTitles:nil] autorelease] show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
// Do anything you want with it
[responseText release];
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
//I'm using HTTP Digest Authentication in your case it could be different
NSURLCredential *credential = [NSURLCredential credentialWithUser:HTTP_DIGEST_USER
password:HTTP_DIGEST_PASSWORD
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
Hope it will help
This error occurs when your are passing wrong bundle or document directory path to media.
Just simply verify your media path to the HTTP request body.
Related
I try to convertNSDictionary to JSON data and sent it to PHP.server in "POST" request with setHTTPBody.
I received a null from the server when I sent from my app, but when I send the JSON from PostMan I receive the objects.
Where am I wrong ?
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
NSString *url = [NSString stringWithFormat:#"http://myAddress/sql_service.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSArray *arrayOfStrings = #[#"alex",#"dima"];
NSDictionary *dict = #{#"request_type" : #"select_with_params",
#"table" : #"user",
#"where" : #"f_name=? OR f_name=?",
#"values" : arrayOfStrings};
NSData* jsonData1 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
[request setHTTPBody:jsonData1];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (data)
{
[receivedData appendData:data];
}
else
{
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError * error = nil;
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&error];
NSLog(#"connectionDidFinishLoading");
}
this is the json i need to post.
{
request_type: "select_with_params",
table: "user",
where: "f_name=? OR f_name=?",
values: ["dima", "alex"]
}
jsonData1 is not nil.
the data in didReceiveData is :
Try AFNetworking
EDIT
NSString *url = [NSString stringWithFormat:#"http://myAddress/sql_service.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSArray *arrayOfStrings = #[#"alex",#"dima"];
NSDictionary *dict = #{#"request_type" : #"select_with_params",
#"table" : #"user",
#"where" : #"f_name=? OR f_name=?",
#"values" : arrayOfStrings};
NSData* jsonData1 = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error];
[request setHTTPBody: [[NSString stringWithFormat:#"%#", jsonData1] dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
if (responseObject)
{
NSLog(#"Success!");
}} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error");
}];
[op start];
Hope this helps
Im trying to post to php and get the response. The php file has an echo "hello" which should just print hello. I'm trying to test to see if posting is working but in my error log the NSlog doesn't display anything:
#interface ViewController ()
#end
#implementation ViewController
#synthesize email, password,receivedData;
-(IBAction)Login:(id)sender{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.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:#"%#", email];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//initialize convert the received data to string with UTF8 encoding
NSString *htmlSTR = [[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding];
NSLog(#"%#" , htmlSTR);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"%#" , error);
}
Since you did not mention about what kind of body type you want to use this example shows you how to post multipart/form-data request.
-(NSString *)generateRandomBoundryString {
CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef UUIDString = CFUUIDCreateString(kCFAllocatorDefault,UUID);
NSString *aNSString = (__bridge NSString *)UUIDString;
CFRelease(UUID);
CFRelease(UUIDString);
return aNSString;
}
-(IBAction)Login:(id)sender {
NSString *bndry = [self generateRandomBoundryString];
NSString *contentType = [[NSString alloc] initWithString:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", bndry]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://grouporder.site90.net/test.php"]];
[request setHTTPMethod:#"POST"];
[request setValue: contentType forHTTPHeaderField:#"Content-Type"];
//form-data block
NSMutableData *requestBody = [NSMutableData data];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"name", #"John"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"%#=%#", #"password", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:requestBody];
//form-data block
// NSURLConnection Asynchronous Block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rspreportStatus, NSData *datareportStatus, NSError *e)
{
if (e == nil)
{
// If all ok you can processes response data here.
}
else {
NSLog(#"%#", e.localizedDescription);
}
}];
}
If body is application/x-www-form-urlencoded you should change Content-Type value like this.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
and replace //form-data block block with this.
[requestBody appendData:[[NSString stringWithFormat:#"name=%#&password=%#", #"John", #"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
#"John" and #"myPassword" has to be URL encoded.
I'm trying to login to a website and get a response using JSON using this code:
#try {
if([[txtUsername text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[txtUsername text],[txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"https://yedion.afeka.ac.il/yedion/fireflyweb.aspx?prgname=login"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
NSLog(#"%d",success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
} else {
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
} else {
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}
In the log I can see there is no JSON response so I can't know if the login was successful or not.
Is there any other way to login to this website and get a response wether or not it was successful?
Thanks!
The code seems ok to me but do check the web service and also check that you give correct keywords for json if the key given to the objectForKey and your key in web service are different you will never get a json response.
Use Get method and try
[ request setHTTPMethod:#"GET" ];
I'm working on a simple prototype and need to test sending push notifications from one device to another.
I've emailed Urban Airship to turn on the "Allow Push From Device" for my application - and they did turn it on.
I'm trying to use NSURLConnection to send the push notification from the device.
This is my code:
- (void) test {
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary * push = #{#"device_tokens":#[#"<token>"], #"aps":#{#"alert":#"TEST", #"sound":#"default"}};
NSData * pushdata = [NSJSONSerialization dataWithJSONObject:push options:0 error:NULL];
[request setHTTPBody:pushdata];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void) connection:(NSURLConnection *) connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *) challenge {
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodHTTPBasic]) {
NSURLCredential * credential = [[NSURLCredential alloc] initWithUser:#"<app key>" password:#"<app secret>" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
[credential release];
}
}
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse * res = (NSHTTPURLResponse *) response;
NSLog(#"response: %#",res);
NSLog(#"res %i\n",res.statusCode);
}
Anyone else done this successfully?
Taking a look at Urban Airship's guide to troubleshooting HTTP status codes, and the documentation for the push API, my guess would be that you need to add a trailing slash to the URL:
[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]
Example Using the V3 API...
-(void)richPushNotification{
NSDictionary *push = #{
#"audience" : #{
#"device_token" : deviceToken
},
#"device_types" : #[ #"ios" ],
#"notification" : #{
#"ios" : #{
#"alert":Message,
#"sound":#"default",
#"badge":#"auto",
}
},
#"message": #{
#"title": Message,
#"body": #"<html><body><h1>blah blah</h1> etc...</html>",
#"content_type": #"text/html",
#"extra": #{
#"offer_id" : #"608f1f6c-8860-c617-a803-b187b491568e"
}
}
};
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/vnd.urbanairship+json; version=3;" forHTTPHeaderField:#"Accept"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", appKey, appMasterSecret];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:push
options:0 // Pass 0 if you don't care about the readability of the generated string
error:NULL];
request.HTTPBody = jsonData;
[NSURLConnection connectionWithRequest:request delegate:self];
}
And The Response:
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse * res = (NSHTTPURLResponse *) response;
NSLog(#"response: %#",res);
NSLog(#"res %li\n",(long)res.statusCode);
if (res.statusCode == 202) {
//Show Alert Message Sent
}else{
//Handle Error
}
}
I am developing view based application.I have login page when we click on Login button it should check entered values with webserver values and it should display vali or invalid.I have wriiten code in this way it is executing successfully i am getting the result in this way
<!DOCTYPE html PUbLIC" -//W3C//DTD XHTML 1.0 Strict....
What i need to change in below code to comapre with server values..can any one help me regarding this please...
-(IBAction)buttonClick:(id)sender
{
NSString* username = nameInput.text;
NSString* pass = passInput.text;
if([nameInput.text isEqualToString:#"" ]|| [passInput.text isEqualToString:#""])
{
greeting.text = #"Input Your Value";
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
return;
}
NSString *post =
[[NSString alloc] initWithFormat:#"uname=%#&pwd=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"https://108.16.210.28/Account/LogOn"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus);
greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
- (void)dealloc {
[super dealloc];
}
#end
Use statusCode to see the login state.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *theResponse = (NSHTTPURLResponse*)response;
NSInteger theStatusCode = [theResponse statusCode];
}
}
you have to parse the data.If it is in the form of XML data then you have to parse the element (like valid) in the didfoundcharacters.If it is valid then make a variable like BOOL confirm = NO;Modify this in the didfoundcharacters.if (confirm) then give access further