Currently i am working in iPhone application, Using JSON to send a request and get response to read it.
Request (example url):
http://www.Genifer.com/index.php?q=api/username-available&username=stephen
I refer the Response from browser (Firefox):
{"status":true,"result":true}
I tried in xcode:
NSString *urlString = [NSString stringWithFormat:#" http://www.Genifer.com/index.php?"];
NSString *parameter = [NSString stringWithFormat:#"q=api/username-available&username=stephen"];
NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:parameterData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if( connection )
{
mutableData = [[NSMutableData alloc] init];
}
else
{
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
NSLog(#"mutableData:%#",mutableData);
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
NSLog(#"mutableData:%#",mutableData);
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[mutableData release];
[connection release];
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonStr = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
NSLog(#"JSonSTr : %#", jsonStr);
}
Response comes:
JSonSTr : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
i refer the request in Firefox browser get the response like {"status":true,"result":true}.
But i tried to integrate same request in xcode, but the response comes different, How to fix this?
Please help me
Thanks in Advance
Can you check with this
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString JSONValue];
Check what values pop up in your dictionary by doing something like this
NSDictionary *question = [jsonDict objectForKey:#"status"];
Related
I have trouble finding info on this topic. Please help me out here.
I need to pass arguments via POST or GET method to my web server and get a reply.
Basically, if using GET method, I want to do something like server.com/?user=john&password=smith and receive the dynamically generated HTML code that is done with my php script. All this without using the web browser on my app.
How is it usually done?
You'll want to look into NSMutableURLRequest and NSURLConnection.
For example, you could use them like this do to a GET request to your server:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// GET
NSString *serverURL = [NSString stringWithFormat:#"http://yourserver.com/login.php?user=%#&pass=%#", username, password];
NSURL *url = [NSURL URLWithString:serverURL];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
This will send an asynchronous GET request to your server with the query string containing username and password.
If you want to send username and password using a POST request, the method would look something like this:
- (void)loginUser:(NSString *)username withPassword:(NSString *)password {
// POST
NSString *myRequestString = [NSString stringWithFormat:#"user=%#&pass=%#",username,password];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSURL *url = [NSURL URLWithString:#"http://yourserver.com/login.php"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod: #"POST"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[req setHTTPBody: myRequestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:req delegate:self];
if (connection) {
connectionData = [[NSMutableData alloc] init];
}
}
In order to get the response from the server, you will need to implement the NSURLConnection delegate methods, for example:
#pragma mark -
#pragma mark NSURLConnection delegate methods
#pragma mark -
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// Called if you have an .htaccess auth. on server
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:#"your_username" password:#"your_password" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[connectionData setLength: 0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[connectionData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connectionData release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[connectionData bytes]
length:[connectionData length] encoding: NSUTF8StringEncoding];
// This will be your server's HTML response
NSLog(#"response: %#",content);
[content release];
[connectionData release];
}
References:
NSMutableURLRequest Class Reference
NSURLConnection Class Reference
Hope this helps :)
Usually this is done using a NSURLConnection. You can also use NSString's method stringWithContentsOfURL.
I am new to iPhone app development. How can I post data and get data by accessing the asmx web service using iPhone app?
I think asmx webservices are SOAP webservices you should read my blog entry here -
http://www.makebetterthings.com/iphone/call-soap-web-service-from-iphone/
To call a SOAP service first i create a string with the SOAP request as follows.
NSString *soapMessage = #"<?xml version="1.0" encoding="utf-8"?>n"
"<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">n"
"<soap:Body>n"
"<CelsiusToFahrenheit xmlns="http://tempuri.org/">n"
"<Celsius>50</Celsius>n"
"</CelsiusToFahrenheit>n"
"</soap:Body>n"
"</soap:Envelope>n";
After creating the SOAP request I create a NSMutableRequest to send this request to server.
NSURL *url = [NSURL URLWithString:#"http://w3schools.com/webservices/tempconvert.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
After firing the request we can collect the XML response in the NSURLConnection’s delegate methods.
-(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
{
NSLog(#"ERROR with theConenction");
[connection release];
[webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",theXML);
[theXML release];
}
After collecting the XML response in theXML string in -(void)connectionDidFinishLoading:(NSURLConnection *)connection
we can parse this string using TBXML for any other XML parser you like.
How can I improve this code?
This question is related to What is the last function in iPhone application lifecycle
-(void)LogoutUser
{
int userId = [[GlobalData sharedMySingleton] getUserId];
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>...", userId
];
NSURL *url = [NSURL URLWithString: #"http://....asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[req addValue:#"http://..." forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [[NSMutableData data] retain];
}
}
-(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
{
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
[theXML release];
[connection release];
[webData release];
}
The problem is that when your application switches to the background state, it no longer receives any network updates. If you require the network call to return before the application enters the background, maybe a synchronous call will help you there.
If you decide to go this route, I also suggest to look at ASIHTTPRequest because those classes will allow you to set a timeout on the synchronous call while the normal NSURLConnection classes won't. Otherwise you risk that your application will be terminated by the iOS if the server does not respond.
I am new to web services in iphone.
I fallow this tutorial
my code is as fallows
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GenericAndroidMethod xmlns=\"Mortgage\">"
"<methodName>MortgageGetLoanOfficerInfo</methodName>"
"<xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam>"
"</GenericAndroidMethod>"
"</soap:Body>"
"</soap:Envelope>"
];
NSLog(#"%#",soapMsg);
NSURL *url = [NSURL URLWithString:#"http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
[req addValue:#"Mortgage/GenericAndroidMethod"forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength
forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
NSLog(#"connected %#",conn);
webData = [[NSMutableData data] retain];
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSLog(#"connect %#",connection);
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
NSLog(#"test %#",data);
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
NSLog(#"error will occer %#",error);
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSLog(#"recived data %#",webData);
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(#"%#",theXML);
[theXML release];
[connection release];
[webData release];
}
In Console i got
2010-12-20 11:23:50.754 Hello_SOAP[1911:40b] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GenericAndroidMethod xmlns="Mortgage"><methodName>MortgageGetLoanOfficerInfo</methodName><xmlParam><MortgageGetLoanOfficerInfo><PhoneNumber>919703661366</PhoneNumber></MortgageGetLoanOfficerInfo></xmlParam></GenericAndroidMethod></soap:Body></soap:Envelope>
2010-12-20 11:23:50.963 Hello_SOAP[1911:40b] connected <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.375 Hello_SOAP[1911:40b] connect <NSURLConnection: 0x5d3dc30, http://10.10.8.7/MobileGenericWebservice/GenericWebService.asmx>
2010-12-20 11:23:51.376 Hello_SOAP[1911:40b] DONE. Received Bytes: 0
2010-12-20 11:23:51.377 Hello_SOAP[1911:40b] recived data <>
in connection didReceiveData i did n't get any data
can any one pls help me why i did n't receive data.
Thank u in advance.
NSString *soapMsg =
[NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GenericAndroidMethod xmlns=\"Mortgage\">"
"<methodName>string</methodName>"
"<xmlParam>string</xmlParam>"
"</GenericAndroidMethod>"
"</soap:Body>"
"</soap:Envelope>"
];
NSLog(#"%#",soapMsg);
NSURL *url = [NSURL URLWithString:#"http://173.31.193.92/MobileGenericWebservice/GenericWebService.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMsg length]];
[req addValue:#"text/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
[req addValue:#"Mortgage/GenericAndroidMethod"forHTTPHeaderField:#"SOAPAction"];
[req addValue:msgLength
forHTTPHeaderField:#"Content-Length"];
[req setHTTPMethod:#"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn) {
NSLog(#"connected %#",conn);
webData = [[NSMutableData data] retain];
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSLog(#"connect %#",connection);
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
// NSLog(#"test %#",data);
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
NSLog(#"error will occer %#",error);
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSLog(#"DONE. Received Bytes: %d", [webData length]);
NSLog(#"recived data %#",webData);
NSString *theXML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
//---shows the XML---
NSLog(#"%#",theXML);
[theXML release];
[connection release];
[webData release];
}
The response and the logs are as follows:
2010-12-23 11:39:55.240 backGroundTest[1260:207] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><GenericAndroidMethod xmlns="Mortgage"><methodName>string</methodName><xmlParam>string</xmlParam></GenericAndroidMethod></soap:Body></soap:Envelope>
2010-12-23 11:39:55.245 backGroundTest[1260:207] connected <NSURLConnection: 0x4b4c220, http://173.31.193.92/MobileGenericWebservice/GenericWebService.asmx>
2010-12-23 11:39:56.105 backGroundTest[1260:207] connect <NSURLConnection: 0x4b4c220, http://173.31.193.92/MobileGenericWebservice/GenericWebService.asmx>
2010-12-23 11:39:56.106 backGroundTest[1260:207] DONE. Received Bytes: 530
2010-12-23 11:39:56.107 backGroundTest[1260:207] recived data <3c3f786d 6c207665 7273696f 6e3d2231 2e302220 656e636f 64696e67 3d227574 662d3822 3f3e3c73 6f61703a 456e7665 6c6f7065 20786d6c 6e733a73 6f61703d 22687474 703a2f2f 73636865 6d61732e 786d6c73 6f61702e 6f72672f 736f6170 2f656e76 656c6f70 652f2220 786d6c6e 733a7873 693d2268 7474703a 2f2f7777 772e7733 2e6f7267 2f323030 312f584d 4c536368 656d612d 696e7374 616e6365 2220786d 6c6e733a 7873643d 22687474 703a2f2f 7777772e 77332e6f 72672f32 3030312f 584d4c53 6368656d 61223e3c 736f6170 3a426f64 793e3c47 656e6572 6963416e 64726f69 644d6574 686f6452 6573706f 6e736520 786d6c6e 733d224d 6f727467 61676522 3e3c4765 6e657269 63416e64 726f6964 4d657468 6f645265 73756c74 3e266c74 3b4e6577 44617461 53657426 67743b0d 0a202026 6c743b47 55494454 61626c65 2667743b 0d0a2020 2020266c 743b4755 49442667 743b3635 37343664 33382d39 3464322d 34306433 2d613636 322d3633 31353765 65346263 6436266c 743b2f47 55494426 67743b0d 0a202026 6c743b2f 47554944 5461626c 65266774 3b0d0a26 6c743b2f 4e657744 61746153 65742667 743b3c2f 47656e65 72696341 6e64726f 69644d65 74686f64 52657375 6c743e3c 2f47656e 65726963 416e6472 6f69644d 6574686f 64526573 706f6e73 653e3c2f 736f6170 3a426f64 793e3c2f 736f6170 3a456e76 656c6f70 653e>
2010-12-23 11:39:56.108 backGroundTest[1260:207] <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GenericAndroidMethodResponse xmlns="Mortgage"><GenericAndroidMethodResult><NewDataSet>
<GUIDTable>
<GUID>65746d38-94d2-40d3-a662-63157ee4bcd6</GUID>
</GUIDTable>
</NewDataSet></GenericAndroidMethodResult></GenericAndroidMethodResponse> </soap:Body></soap:Envelope>
I beleive the problem is with the ip setting. check it out again please.
try to see the headers from the didReceiveResponse method
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog([dictionary description]);
}
see the description. It might give the response header received from the server. It contains Length parameter. If it is 0, the server is returning no data to the app. One possible work around will be to change the header for the request.
Note that the connection didReceiveData is not getting called. There might be a potential error in sending the response from the server. Try and simulate the same testing parameters of the soap service from external links and see the response. You can also verify it in the didReceiveResponse method by extracting the response code for the NSURLResponse.
I beleive the error is due to the inappropriate formatting of the data being sent.
I have a WCF service hosted and I'm trying to use it within an iPhone app as a JSON POST request. I plan on using the JSON serializer later, but this is what I have for the request:
NSString *jsonRequest = #"{\"username\":\"user\",\"password\":\"letmein\"}";
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://mydomain.com/Method/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
In my data received I'm just printing it to the console:
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableData *d = [[NSMutableData data] retain];
[d appendData:data];
NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", a);
}
And within this response I get this message:
Data: <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Request Error</title>
<style>
<!-- I've took this out as there's lots of it and it's not relevant! -->
</style>
</head>
<body>
<div id="content">
<p class="heading1">Request Error</p>
<p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="https://mydomain.com/Method/help">service help page</a> for constructing valid requests to the service.</p>
</div>
</body>
</html>
Does anyone know why this happens and where I'm going wrong?
I've read about using ASIHTTPPost instead but I can't get the demo to run in iOS4 :(
Thanks
EDIT:
I've just used to CharlesProxy to sniff out what's happening when I call from the iPhone (Simulator) and this is what it gave me:
The only thing strange I've noticed is it says "SSL Proxying not enabled for this host: enable in Proxy Settings, SSL locations". Does anyone know what this means? (This also happens in my working windows client).
I've just ran this on my windows client and the only thing that is different is the Request and Response text which is encrypted. Am I missing something in order to use a secure HTTP connection to do this?
NEW EDIT:
This works with a non-HTTPS request such as:
http://maps.googleapis.com/maps/api/geocode/json?address=UK&sensor=true. So I guess the problem is getting the iPhone to send the POST properly over SSL?
I am also using these methods:
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
return YES;
}
}
This allows me to get this far. If I don't use them I get an error sent back saying:
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “mydomain.com” which could put your confidential information at risk.
FIXED!
Changed:
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
to:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
You also need these two methods:
- (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
return YES;
}
}
I don't know Objective C at all, but try setting the Accept header to application/json instead of application/jsonrequest.
change
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
to
NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
dic is NSMutable Dictionary with object and keys.
baseUrl is your server webservice url.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *encodedString = [jsonString base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:encodedString forHTTPHeaderField:#"Data"];