Im trying to get answer (an image) from a service on a PC with a HTTP GET request.
If I put the request into a webbrowser, I get the requested image. If I try to get it in iPhone app, it doesnt work.
the request is:
http://192.168.151.82:54000/snapshot?s=<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/
my code for getting is:
NSString *str = [NSString stringWithFormat: #"http://192.168.151.82:54000/snapshot?s=<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/"];
NSURL *url = [[NSURL alloc] initWithString:str];
UIImage *img = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];
You can see, that speciel characters like quotes and percentes are handeled.
Im watching network communication on the PC with wireshark and there isn't any communication.
You need to url encode your parameters before creating a url from them
NSString * unencodeParameter = #"<snapshotrequest xmlns=\"http://www.vizrt.com/snapshotrequest\"><videomoderequest><width>880</width><height>495</height></videomoderequest><snapshotdata view=\"all\"/></snapshotrequest>&p=http://192.168.151.82:8580/element_collection/storage/shows/%%257B3646FFAC-4E77-41AB-BDFC-F581D157ABA3%%257D/elements/1000/";
NSString * encodedParameter = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedParameter,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );
NSString *str = [NSString stringWithFormat: #"http://192.168.151.82:54000/snapshot?s=%#",encodedParameter];
NSURL *url = [[NSURL alloc] initWithString:str];
UIImage *img = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];
And also make sure your iPhone is on same wifi as your computer as you are using local IP address
Related
I am trying to url encode a string, but the NSURLConnection is failing because of a 'bad url'. Here is my URL:
NSString *address = mp.streetAddress;
NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *cityState= mp.cityState;
NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fullAddressURL = [NSString stringWithFormat:#"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%#&citystatezip=%#", encodedAddress, encodedCityState];
NSURL *url = [NSURL URLWithString:fullAddressURL];
Here is the API's example of calling the URL:
Below is an example of calling the API for the address for the exact address match "2114 Bigelow Ave", "Seattle, WA":
http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA
For some reason this URL is failing to connect. Can someone help me out?
You have to encode your fullAddressURL before sending that to NSURL instead of encoding address & cityState individually.
NSString *address = #"2114 Bigelow Ave";
//NSString *encodedAddress = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *cityState= #"Seattle, WA";
// NSString *encodedCityState = [cityState stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *fullAddressURL = [NSString stringWithFormat:#"http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<X1-ZWz1bivd5de5mz_8xo7s>&address=%#&citystatezip=%#", address, cityState];
fullAddressURL = [fullAddressURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"fullAddressURL: %#",fullAddressURL);
NSURL *url = [NSURL URLWithString:fullAddressURL];
I have tested above code and it is giving me same output as given link http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=<ZWSID>&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA
I have searched a lot on google as well as on stackoverflow but did not get any satisfactory solution which works for me.
I have to upload an image on some particular url which is ending with extension .ashx.
I have seen how to upload on php server but here i am not getting any clue.
Please help me by providing some sample code.
As per my understanding aspx is the page and the .ashx is the code file which response back the output, in string format and .ashx file is a web handler. A web handler file works just like an aspx file....
So we consider.ashx same as .aspx then this code should work for you(which is running for me for .aspx page). This is making request to .net server.
iOS
UIImage *img = [UIImage imageNamed:#"test.png"];
NSData *imageData = UIImageJPEGRepresentation ( img , 90 );
NSString *urlString =#"www.xyz.com/ImageUpload.aspx?filename=test";
NSLog(#"IMAGE_UPLOAD_URL -------------> %#",urlString);
NSMutableURLRequest *request = [[[ NSMutableURLRequest alloc ] init ] autorelease ];
[request setURL :[ NSURL URLWithString :urlString]];
[request setHTTPMethod : #"POST" ];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [ NSString stringWithFormat : #"multipart/form-data; boundary=%#" ,boundary];
[request addValue :contentType forHTTPHeaderField : #"Content-Type" ];
/* body of the post */
NSMutableData *body = [ NSMutableData data ];
[body appendData :[ NSData dataWithData :imageData]];
[request setHTTPBody :body];
NSData *returnData = [ NSURLConnection sendSynchronousRequest :request returningResponse : nil error : nil ];
NSString *returnString = [[ NSString alloc ] initWithData :returnData encoding : NSUTF8StringEncoding ];
InfoLog(#"_______ IMAGE_UPLOAD response -------------> .%#.",returnString);
.NET
Retrieving image like this for .aspx page
if (Request.QueryString["filename"] != null)
{
string filename = Request.QueryString["filename"].ToString();
string saveFilePath = ConfigurationManager.AppSettings["CPSBImageFolder"].ToString();
//string saveFilePath = Server.MapPath("~/images");
saveFilePath = saveFilePath + filename;
Stream objStream = Request.InputStream;
StreamReader objStreamReader = new StreamReader(objStream);
Image image = Image.FromStream(objStreamReader.BaseStream, true);
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters param = new EncoderParameters(1);
param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
image.Save(saveFilePath, info[1], param);
Response.Write("true");
}
Not sure but hope this give you a clue.
Verify that the variable(NSData) you are using to upload image is not null & your dot net server is receiving request.
I use Flickr API for my app to manage user's photo. I decided to make authentication using Apple's classes and it works fine for me. Now my app is authenticated and has all necessary tokens and secret keys so it's possible to perform GET requests with authentication for methods like flickr.photos.search, flickr.test.login and so on.
But I spent a few days trying to perform upload using http://api.flickr.com/services/upload/
and their instructions here.
They say that request should have argument 'photo' and this parameter should not be included in the signature. That is clear, but I have no idea how to implement this parameter the request.
#import "FlickrUploader.h"
#import "HMACSH1.h"
#import "Prefs.h"
#import "NSString+URLEncode.h"
#implementation FlickrUploader
- (void)uploadPhotoAtPath:(NSString*)filePath {
NSString *upload_api_url = #"http://api.flickr.com/services/upload/";
NSString *oauth_nonce = [NSString stringWithFormat:#"%d", 10000000 + arc4random()%1000000];
NSString *oauth_timestamp = [NSString stringWithFormat:#"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *oauth_consumer_key = CONSUMER_KEY;
NSString *oauth_signature_method = #"HMAC-SHA1";
NSString *oauth_version = #"1.0";
NSString *oauth_token = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_ACCESS_TOKEN_KEY];
//creating basestring to make signature without a 'photo' argument according to API
NSMutableString *basestring = [[NSMutableString alloc] initWithCapacity:8];
[basestring appendFormat:#"&oauth_consumer_key=%#",oauth_consumer_key];
[basestring appendFormat:#"&oauth_nonce=%#",oauth_nonce];
[basestring appendFormat:#"&oauth_signature_method=%#",oauth_signature_method];
[basestring appendFormat:#"&oauth_timestamp=%#",oauth_timestamp];
[basestring appendFormat:#"&oauth_token=%#", oauth_token];
[basestring appendFormat:#"&oauth_version=%#",oauth_version];
//this is may class to make HMAC-SHA1 signature (it works for authentication and for GET requests)
HMACSH1 *hMACSH1 = [[HMACSH1 alloc] init];
NSMutableString *urlEncodedBaseString = [[NSMutableString alloc] initWithCapacity:3];
[urlEncodedBaseString appendString:#"POST"];
[urlEncodedBaseString appendFormat:#"&%#",[upload_api_url urlEncodedString]];
[urlEncodedBaseString appendFormat:#"&%#",[basestring urlEncodedString]];
NSString *oauth_token_secret = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_TOKEN_SECRET_KEY];
NSString *hash_key = [CONSUMER_SECRET stringByAppendingFormat:#"&%#",oauth_token_secret];
NSString *oauth_signature = [hMACSH1 hmacSH1base64ForData:urlEncodedBaseString keyValue:hash_key];
//creating url for request
NSMutableString *urlString = [[NSMutableString alloc] initWithCapacity:8];
[urlString appendFormat:#"%#",upload_api_url];
[urlString appendFormat:#"?"];
[urlString appendString:basestring];
[urlString appendFormat:#"&oauth_signature=%#", oauth_signature];
NSURL *authURL = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
request.HTTPMethod = #"POST";
UIImage *img = [UIImage imageNamed:filePath];
NSData *imgData = UIImageJPEGRepresentation(img, 0.8);
//here I don't know what to do :((( perhaps NSOutputStream
}
This is my JSON response:
{"#error":false,
"#data":
{"personal_info":
{"basic_information":
{"EmailAddress":"k_bhuvaneswari#hcl.com",
"PasionProfessional":null,
"PasionPersonal":null,
"WorkLocation":"Chennai-AMB-6, Amb. Ind. Est., MTH Rd, 8",
"Country":null,
"City":null,
"Latitude":null,
"Longitude":null,
"Title":"Software Engineer",
"HomeTown":null,
"RelationshipStatus":null,
"BriefBio":null,
"FavouriteQuotation":null},
"education":
{"HighSchool":null,
"HighSchoolYear":null,
"HigherSecondary":null,
"HSSYear":null,
"DiplomaTechnical":null,
"DiplomaInsitute":null,
"YearofDiploma: ":null,
"Degree":null,
"YearofPassing":null,
"College/University":null,
"PostGraduation":null,
"YearofPostGraduation":null,
"PGCollege/University":null},
"interest":
{"Keywords":null},
"contact_information":
{"MobilePhone":"9791729428",
"BusinessCode":null,
"BusinessPhone":null,
"OtherCode":null,
"OtherPhone":null,
"Website":null}},
"work_profile_info":
{"profile_title":"",
"profile_bio":""},
"boolean":"1"}}
Now I want to display labels programmatically like this:
EmailAddress k_bhuvaneswari#hcl.com
PasionProfessional Nil
How can I do that?
Very easy. You need a JSON library that allows you to parse the data you recieve. I personally like JSONKit.
NSURL *url = [NSURL URLWithString:#"http://url.com"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *dict = [data objectFromJSONString]; //JSONKit
Then you can just step down the structure and grab the stuff you want:
NSString *email = [dict valueForKeyPath:#"#data.personal_info.basic_information. EmailAddress"];
I have a servlet that serves up a plist XML file. What's the best way to slup this into an NSDictionary? I have this basically working with:
NSDictionary* dict = [ [ NSDictionary alloc] initWithContentsOfURL:
[NSURL URLWithString: #"http://example.com/blah"] ];
But then I have no control over the timeout; I'd rather not have my UI hang for 60 seconds just because the server (which I may not control) is having a hissy fit. I know about NSURLRequest, which will let me do the following:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString: #"http://example.com/blah"
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5 ];
But I don't quite see how to feed that to NSDictionary.
You need to do this using the asynchronous methods. Start with this answer/post:
Can I make POST or GET requests from an iphone application?
This will get you your data and place it in a varibale: responseData. Now you need to add your code to convert it to a NSDictionary in the following method:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
I've found 2 possible ways to convert NSData to NSDictionary. This way is straight from the Apple Archives and Serializations Guide.
NSString *errorStr = nil;
NSPropertyListFormat format;
NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData: responseData
mutabilityOption: NSPropertyListImmutable
format: &format
errorDescription: &errorStr];
Second:
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSDictionary *dictionary = [string propertyList];
[string release];