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>
Related
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.
I have to connect to a URL to check whether the records is empty. The response looks something like this:
<?xml version = "1.0" encoding = "UTF-8"?>
<find>
<record_id>1234</record_id>
<no_record>00001</no_record>
<entry_num>00001</entry_num>
<session-id>aijheifaohqrihelrkqn324tlejaofjaf</session-id>
</find>
My codes:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
autorelease];
[request setURL:[NSURL URLWithString: finalSearchURL]];
// Content-Type related.
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
// Create Connection.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
// The connection was established.
NSMutableData *receivedData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:request]];
NSLog( #"Data will be received from URL: %#", request.URL );
NSLog(#"Recieved Data 2: %#", receivedData);
}
else
{
// The download could not be made.
NSLog( #"Data could not be received from: %#", request.URL );
}
But it returns me:
Recieved Data : <3c3f786d 6c207665 7273696f 6e203d20 22312e30 2220656e 636f6469 6e67203d 20225554 462d3822 3f3e0a3c 66696e64 3e0a3c73 65745f6e 756d6265 723e3031 39303633 3c2f7365 745f6e75 6d626572 3e0a3c6e 6f5f7265 636f7264 733e3030 30303030 3030313c 2f6e6f5f 7265636f 7264733e 0a3c6e6f 5f656e74 72696573 3e303030 30303030 30313c2f 6e6f5f65 6e747269 65733e0a 3c736573 73696f6e 2d69643e 4d505843 33323433 58564336 4534454a 41464232 45473541 39374237 584e3832 43554631 4e314234 584e4c37 424c5947 4e533c2f 73657373 696f6e2d 69643e0a 3c2f6669 6e643e0a 20>
Can anyone help to tell me what am I doing wrong? This is my first attempt for getting response from a url please help thanks!
See the data as a string this way:
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"the xml string is %#", string);
If the parsing goal is simple enough - like just to find the value of one tag - you can use string methods to parse. Otherwise, NSXMLParser or several other options are available.
To see if the string contains a substring, you can do something like this:
if (string) {
NSRange range = [string rangeOfString:#"<session-id>"];
if (range.location != NSNotFound) {
// session-id tag is at index range.location, so we know it's there
}
}
The method you used is to get the raw data from the url. You need a parser to convert the raw data to the understandable structure (probably NSDictionary rather than NSArray).
Apple has provided NSXMLParser for you to retrieve the xml structure from the url or you can find other xml parser libraries.
Actually, your code is returning the correct data. Since NSData can hold any kind of data, it will just display the hex value. If you convert the hex data to a sting, you'll see that it has the correct text.
Now, your code can be simplified a lot. All the code for setting up the NSURLConnection is not needed at all. All you need is the following line.
NSString *recievedText = [NSString stringWithContentsOfFile:finalSearchURL encoding:NSUTF8StringEncoding error:NULL];
I am calling a URL through POST HTTP method. When I am not connected to 3G or WiFi, it will never fetch the URL correctly and will never get the response from the URL correctly.
Connection is made through post:
NSString *URL = [NSString stringWithFormat:#"http://www.abc.com/webservices/client_server.cfc];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *time_stamp =[NSString stringWithFormat:#"time_stamp=%#", self.today];
NSData *postData = [time_stamp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *URLRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[URLRequest setURL:[NSURL URLWithString:URL]];
[exhURLRequest setHTTPMethod:#"POST"];
[URLRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[URLRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[URLRequest setHTTPBody:postData];
self.connection =[[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.connection != nil, #"Failure to create URL connection.");
I am checking if I get the response through :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (([httpResponse statusCode]/100) == 2) {
self.data = [NSMutableData data];
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(#"HTTP Error",
#"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
[self handleError:error];
}
}
But some how when the URL is not connected lets say when I am in the metro or something, I cannot connect to URL and it throws me "URL NOT SUPPORTED". How can I avoid such a scenario and allow the app to push forward without throwing such an error ? If anybody has used offline redirection to the app without keep on waiting the user on the front screen.
Download appleās Reachability sample code. Add Reachability.h+.m to your project. Link SystemConfiguration framework. Then use their Reachability class like so.
#import "Reachability.h"
for WiFi:
-(void)doStuff{
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
if (wifi.currentReachabilityStatus == ReachableViaWiFi){
// do connected stuff
}
else {
// do offline stuff
}
}
For Wifi or 3G:
-(void)doStuff{
NetworkStatus connectivity = [Reachability reachabilityForInternetConnection].currentReachabilityStatus;
if (connectivity == ReachableViaWiFi || connectivity == ReachableViaWWAN){
// do connected stuff
}
else {
// do offline stuff
}
}
If you will be continually doing network tasks add the reachability object to your class. That will improve performance and allow you to use it's notifier.
some time this "URL NOT SUPPORTED error" is due to the url not encoding.
for this encode url by using this.or there are lots of ways on internet.
dont encode whole url or base url (as it will encode ":" and '/' too and it may cause errors)
only special charecter needs to be encode like &,# etc.
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)pathRequest,
NULL,
(CFStringRef)#"!*'();:#&=+$,%#[]",
kCFStringEncodingUTF8 ));
How to check for an active Internet connection on iOS or OSX?
Use the solution propsed here to avoid sending a request when you don't have an active internet connection. Simple.
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"];
Is it possible to POST XMLData to the webservices from iPhone OS. The webservices are developed in ASP.net MVC 3.0 with RESTFul url and we would like iPhone developers to send input data in XML format as POST variable..
The webservice actionresult looks like the following where sightings is the parameter that is expected to pass as POST variable
public ActionResult Update(XDocument sightings)
{
try
{
XMLHelper xmlHelper = new XMLHelper();
}
}
That's definitely applicable all you need to do is to use NSMutableURLRequest as the following:
NSString* sXMLToPost = #"<?xml version=\"1.0\"?><Name>user</Name>";
NSData* data = [sXMLToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://myurl.com/RequestHandler.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[sXMLToPost dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (error) {
//handle the error
}
And Now in your ASHX file parse the InputStream to read the posted XML:
System.IO.Stream str; String strmContents;
Int32 counter, strLen, strRead;
str = Request.InputStream;
strLen = Convert.ToInt32(str.Length);
byte[] strArr = new byte[strLen];
strRead = str.Read(strArr, 0, strLen);
// Convert byte array to a text string.
strmContents = "";
for (counter = 0; counter < strLen; counter++)
{
strmContents = strmContents + strArr[counter].ToString();
}
Remember you can always check the request type using:
if (context.Request.RequestType == "POST")
MSDN HttpRequest.InputStream