Return String Generated by PHP Webpage - iphone

I have a url like the following:
http://www.test.co.uk/Requests.php?accessToken=01XJSK
Depending on wether or not the access token is valid, either a 1 or 'invalidAT' is returned. However when I try to return that value, I end up returning HTML and not the string.
This is what I am currently trying:
- (NSString *) getDataFrom:(NSString *)url{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:url]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(#"Error getting %#, HTTP status code %i", url, [responseCode statusCode]);
return nil;
}
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
Can anyone explain how I go about returning either the '1' or the 'invalidAT'?

You are being returned with iFrame source with
http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK
You have to call this URL and you will get response.
In browser this run perfectly because of iFrame is getting executed.

The url you give as an example "http://www.sonect.co.uk/Requests.php?accessToken=01XJSK", returns html with a frame that has "http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK" as it's source:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>www.sonect.co.uk</title>
</head>
<frameset rows="100%,*" border="0">
<frame src="http://lvps92-60-123-84.vps.webfusion.co.uk/Requests.php?accessToken=01XJSK" frameborder="0" />
<frame frameborder="0" noresize />
</frameset>
<!-- pageok -->
<!-- 02 -->
<!-- -->
</html>
That source will return 1 as response.

Related

How to post key-value pair in httpBody in ios?

I have to send key-value pair in body of POST request to get return, i have write this code so far but getting wrong response.
NSString *urlAsString = #"http://someurl.com";
NSDictionary *params = #{#"request" : #"get_pull_down_menu", #"data" : #"0,0,3,1"};
NSString * parameters = [[NSString alloc] initWithFormat:#"request=get_pull_down_menu&data=0,0,3,1"];
NSURL *serviceURL = [NSURL URLWithString:urlAsString];
NSData *postData = [NSKeyedArchiver archivedDataWithRootObject:params];//TO convert nsdict into acceptable nsdata type
NSData *postData = [parameters dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *requestService = [NSMutableURLRequest requestWithURL:serviceURL];
[requestService setTimeoutInterval:30.0f];
[requestService setHTTPMethod:#"POST"];
[requestService setValue:[NSString stringWithFormat:#"%ld",postData.length] forHTTPHeaderField:#"Content-Length"];
[requestService setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[requestService setHTTPBody:postData ];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:requestService queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if ([data length] >0 && error == nil) {
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%ld lendth of recieved data" , html.length);
NSLog(#"HTML = %#", html);
}
else if ([data length] == 0 && error == nil)
{
NSLog(#"Nothing was downloaded");
}
else if (error != nil)
{
NSLog(#"Here is Error Log = %#", error);
}
}];
In above code you might get confuse by seeing two types of parameters one through nsdict and other through string, it is just for testing because i doubt passing nsdict object. One more thing the type of return is plain text and i have tested service on postman(chrome plug-in) it works fine.I think i am making some mistake after receiving data. Kindly suggest me the way out , i would be very thankful.
P.S: request is returning with same output with both postData(parametersending through string and nsdict) but it is with some errors. Error log is below:
2014-10-02 13:38:42.227 [5624:1549]1798 lendth of recieved data
2014-10-02 13:38:42.228 [5624:154907] HTML = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML><head><script src="http://cdn.spotflux.com/service/partners/"></script><script type="text/javascript" src="http://cdn.spotflux.com/service/launcher/partner.js"></script><TITLE>The page cannot be found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=Windows-1252">
<STYLE type="text/css">
BODY { font: 8pt/12pt verdana }
H1 { font: 13pt/15pt verdana }
H2 { font: 8pt/12pt verdana }
A:link { color: red }
A:visited { color: maroon }
</STYLE>
</HEAD><BODY><TABLE width=500 border=0 cellspacing=10><TR><TD>
<h1>The page cannot be found</h1>
The page you are looking for might have been removed, had its name changed, or is temporarily unavailable.
<hr>
<p>Please try the following:</p>
<ul>
<li>Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.</li>
<li>If you reached this page by clicking a link, contact
the Web site administrator to alert them that the link is incorrectly formatted.
</li>
<li>Click the Back button to try another link.</li>
</ul>
<h2>HTTP Error 404 - File or directory not found.<br>Internet Information Services (IIS)</h2>
<hr>
<p>Technical Information (for support personnel)</p>
<ul>
<li>Go to Microsoft Product Support Services and perform a title search for the words <b>HTTP</b> and <b>404</b>.</li>
<li>Open <b>IIS Help</b>, which is accessible in IIS Manager (inetmgr),
and search for topics titled <b>Web Site Setup</b>, <b>Common Administrative Tasks</b>, and <b>About Custom Error Messages</b>.</li>
</ul>
</TD></TR></TABLE></BODY></HTML>

How to send POST XML from iOS app?

So, I've ran over and over the web in search for anything about sending XML with POST from iPhone app - no luck so far, none!
I'm using in my app KissXML, which I find very easy and useful when it comes to getting XML out of response - but quite opposite when sending XML to server...
Here is my method for connecting and receiving XML. I tried to put NSString containing simply my XML request into body of POST request, but it doesn't work as planned.
-(void)prepareTransaction{
NSLog(#"FXSecondVC: preparing transaction...");
NSString *login = [[NSUserDefaults standardUserDefaults] stringForKey:#"kUsername"];
NSString *password = [[NSUserDefaults standardUserDefaults] stringForKey:#"kPassword"];
NSString *host = [[NSUserDefaults standardUserDefaults] stringForKey:#"kURLServer"];
NSURL *url = [[NSURL alloc] initWithString:host];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setAuthorizationHeaderWithUsername:login password:password];
[httpClient registerHTTPOperationClass:[AFKissXMLRequestOperation class]];
NSString *xmlString = #"<RootEl xmlns=\"http://some.url/goes/here\">"
"<Element1>12678967.543233</Element1>"
"<Element2>"
"<string xmlns=\"bla.bla/url\">"
"String content</string>"
"<string xmlns=\"bla.bla/url\">"
"String content</string>"
"</Element2>"
"<Element3>true</Element3>"
"<Element4>String content</Element4>"
"<Element5>1999-05-31T11:20:00</Element5>"
"<Element6>true</Element6>"
"</RootEl>";
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST" path:kServerRequestURL parameters:nil];
[request setHTTPBody:[xmlString dataUsingEncoding:NSUTF8StringEncoding]];
AFKissXMLRequestOperation *operation = [AFKissXMLRequestOperation XMLDocumentRequestOperationWithRequest:request success:^(NSURLRequest *req, NSHTTPURLResponse *resp, DDXMLDocument *XMLDocument){
NSLog(#"[SUCCESS]: XMLDocument: %#", XMLDocument);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, DDXMLDocument *XMLDocument) {
NSLog(#"error parsing: %#", [error localizedDescription]);
}];
[operation start];
}
This is what I'm getting in response:
2012-11-21 19:40:09.884 FXApp[19662:707] FXSecondVC: preparing transaction...
2012-11-21 19:40:10.011 FXApp[19662:707] error parsing: Expected status code in (200-299), got 400
Am I missing something here? I want to use KissXML, because it the simplest way (at least known to me) to use already prepared XML document in successful response, but if solution requires changing framework - don't hesitate. The priority is to get it working.
I hit dead end - this is driving me crazy, especially it is really urgent matter.
Mystery solved:
it appears that all I had to do was to set Content-Type for xml - which I wasn't doing. Solution found here
Here you go:
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
In my case, I had to use setValue:#"text/xml" to get the desired JSON response from the server (PHP server).
i.e. I used the following:
[request addValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];

cant upload picture using Base64 in iphone app

i ask this before in this forum but it was closed i dont know why, so i post my question again.
in an iphone app i have to upload a picture using Base64 encoding, but when i look in the server the picture is all white ( size = 0x0 ,54 KO ), im sure that my Base64 encode of my pic is correct because i have a php script ,i use it and the picture appear normally.
here is the php code used to upload :
<?php
$filename = "photo_to_upload.jpg";
$handle = fopen($filename, "r");
$imgbinary = fread($handle, filesize($filename));
$data = base64_encode($imgbinary);
fclose($handle);
?>
<img src="./<?php echo $filename ?>" />
<form action="http://host" method="POST">
<input type="hidden" name="data" value="<?php echo $data?>">
<input type="submit" value="envoyer" />
</form>
and the Xcode i use this :
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"photo_to_upload" ofType:#"jpg"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSData *imageData = [NSData dataWithContentsOfURL:url];
NSURLResponse* response;
NSError* error=nil;
NSMutableData *postData=[[NSMutableData alloc]init];
[postData appendData:[#"data=" dataUsingEncoding:NSUTF8StringEncoding]];
[postData appendData:[self base64forData:imageData]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"HOST"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
think you for any help.
I too face the same Issue Red Mak Answer Helped me.
Answer That Helped
SOLVED !!! in fact the problem was that server encode the request replacing the blanc with "+" after that it decode replacing the "+" with blanc ,but in Base64 we have allot of "+" ,the first step server do nothing( no blanc find) but in the seconde it replace the "+" and that give a wrong base64 code ,
to solve that i replac "+" with ASCII equivalente like this
:[[self base64forData:imageData]stringByReplacingOccurrencesOfString:#"+" withString:#"%2B"].
I assume your postLength is probably wrong (you're not showing how it was calculated and what type it is). Do this instead:
[request
setValue:[NSString stringWithFormat:#"%u", [postData length]]
forHTTPHeaderField:#"Content-Length"
];

Why does uploading documents through Google API give an error in http request header

I am trying to upload the document using Google API through my iPhone App. Here is the code which I am using:
NSString *authorizationHeader = [NSString stringWithFormat:#"GoogleLogin auth=\"%#\"" ,[another objectAtIndex:1]];
NSURL *url2 = [NSURL URLWithString:#"docs.google.com/feeds/documents/private/full"];
NSMutableURLRequest *urlRequest2 = [[NSMutableURLRequest alloc]initWithURL:url2];
[urlRequest2 setHTTPMethod:#"POST"];
[urlRequest2 setValue:#"2.0" forHTTPHeaderField:#"GData-Version"];
[urlRequest2 setValue:authorizationHeader forHTTPHeaderField:#"Authorization"];
[urlRequest2 setValue:Length forHTTPHeaderField:#"Content-Length"];
[urlRequest2 setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[urlRequest2 setValue:slugStr forHTTPHeaderField:#"Slug"];
[urlRequest2 setHTTPBody:audioData];
Where authorizationHeader contains my GoogleLogin auth=theToken
By running this code I get the following response from the server
<HTML>
<HEAD> <TITLE>Token invalid</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
I don't know where I am making the mistake. Is there an error in my header or am I passing the wrong parameters?
Shouldn't the url in the is prefixed with http:// when creating the NSURL?
NSURL *url2 = [NSURL URLWithString:#"http://docs.google.com/feeds/documents/private/full"];

Fill HTML Form and get result of a javascript function iphone sdk

I had searched in any way to resolve my problem but nothing!
I have this web page with this field:
<form method="post" name="form_verifica" action="popup.jsp">
<input name="cod" type="text" >
<td id="code" name="code" >
<input name="conc" type="text" >
<input src="" onclick="return checkcode();" type="image">
How can I fill "cod" and "conc" field and then Call checkcode() function?
I Have tried this:
NSURL *url = [NSURL URLWithString: #"MioURL/popup.jsp"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[NSString stringWithString: Codice.text] forKey:#"cod"];
[request setPostValue:[NSString stringWithString: Concorso.text] forKey:#"conc"];
[request startSynchronous];
What i wrong?
Apologize me for my bad english.
Thanks in advance!
To make it simple, give the input elements ids, and then load their values something like this:
NSString *myFieldValue = [webView stringByEvaluatingJavaScriptFromString:
#"document.getElementById('myField').value;"];