In iOS development, when using nsurlconnection to request the Google Places API, if the requested URL contains Chinese, the returned result is empty and the URL cannot be recognized by Google.
NSString *_urlstring = @ "Http://maps.googleapis.com/maps/api/geocode/json?address= Nanjing &sensor=true ";
Nsurl *_url = [Nsurl urlwithstring:_datastring];
Nsmutableurlrequest *_request = [Nsmutableurlrequest Requestwithurl:_url];
I'm going to transcode the URL string, and I can't recognize it.
Transcoding method One:
NSString * _datastring = [[NSString alloc] initwithdata:[_urlstring datausingencoding:nsasciistringencoding Allowlossyconversion:yes] encoding:nsasciistringencoding];
Transcoding method Two:
NSString * _datastring=[nsstring stringwithutf8string:[_urlstring utf8string];
This problem is actually a URL encoding and decoding problem.
The iphone can be encoded using stringbyaddingpercentescapesusingencoding.
_urlstring=[_urlstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
NSLog (@ "Address URL:%@", _urlstring);
However, in actual use, the encoded URL may still be invalid. Because URLs are not unique in their coding style.See also: Encode-compare and urlencoding
nsstring* escapedurlstring = [unescapedstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]
Some characters are not encoded under different encoding methods.
Therefore, what encoding the client uses should be paired with the server-side decoding method.
You can use Cfurlcreatestringbyaddingpercentescapes to encode the parameters part of the URL and then use the previous stringbyaddingpercentescapesusingencoding encoding. should be able to adapt to most decoding methods.
There are also many escape characters in the requested URL and need to be handled.
NSString * encodedstring = (NSString *) cfurlcreatestringbyaddingpercentescapes (null, (CFSTRINGREF) Yourtext, NULL, ( CFSTRINGREF) @ "!*" ();: @&=+$,/?%#[] ", kCFStringEncodingUTF8);
Attach some of the usual escape processing:
Under javascript:
Escape character: ' \ '
$ escape for \$
Under XML:
&--> \&
<--> <
>--> >
'-'
"-"
Under SQL (MS Access):
#--> # #
! --!!
'--"
In the case of SOAP-based HTTP service requests, it is often necessary to escape the request information in XML format.
Decoding and escaping URLs in iOS