在ios中使用查询字符串创建NSURLRequest

[英]NSURLRequest creation using query string in ios


I have created one user enquiry form in ios. I'm using php as a server side. I constructed query string like bellow in IOS

我在ios中创建了一个用户查询表单。我使用php作为服务器端。我在IOS中构建了类似bellow的查询字符串

http://www.mydomain.in/androidmail_enquiry.php?name=Vinoth Kumar&phone=04259280244&email=vinoth@ldomain.com&address=Coimbatore&comments=Sample Enquiry&mobile=xxxxxxxx

Code:

代码:

-(void)sendEnquiryDetails
{
    cmttextview.text = @"Sample Enquiry";
    NSString *siteurl = @"http://www.mydomain.in/androidmail_enquiry.php?";
    NSString *name = txtName.text;
    NSString *phone = txtPhone.text;
    NSString *email = txtEmail.text;
    NSString *address = txtAddress.text;
    NSString *comments = cmttextview.text;
    NSString *mobile = txtMobile.text;
    NSString *enquiryurl = [NSString stringWithFormat:@"%@name=%@&phone=%@&email=%@&address=%@&comments=%@&mobile=%@",siteurl,name,phone,email,address,comments,mobile];

    NSLog(enquiryurl);

   NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:enquiryurl]];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request  delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.responseData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",[NSString stringWithFormat :@"didfailwitherror: %@", [error description]]);
}

-(void)connectionDidFinishLoading: (NSURLConnection *)connection{
    NSLog(@"Success Code:%@",self.responseData);
}

But when i submit this by using NSURLRequest getting error like invalid url(URL Forming error) in didFailWithError method.

但是当我通过didFailWithError方法使用NSURLRequest获取错误时,比如无效url(url形成错误)。

3 个解决方案

#1


7  

Make sure You have added stringByAddingPercentEscapesUsingEncoding , because in your url there is space in name , so in browser it is replaced with %20 you have to add programmatically in code,

确保添加了stringByAddingPercentEscapesUsingEncoding,因为在url中有名称空间,所以在浏览器中,它被%20替换为%20,必须以编程方式在代码中添加,

Try this

试试这个

-(void)sendEnquiryDetails
{
    cmttextview.text = @"Sample Enquiry";
    NSString *siteurl = @"http://www.mydomain.in/androidmail_enquiry.php?";
    NSString *name = txtName.text;
    NSString *phone = txtPhone.text;
    NSString *email = txtEmail.text;
    NSString *address = txtAddress.text;
    NSString *comments = cmttextview.text;
    NSString *mobile = txtMobile.text;
    NSString *enquiryurl = [NSString stringWithFormat:@"%@name=%@&phone=%@&email=%@&address=%@&comments=%@&mobile=%@",siteurl,name,phone,email,address,comments,mobile];

    NSLog(enquiryurl);

 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[enquiryurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request  delegate:self];
}

#2


5  

You have to percent escape reserved characters. If nothing else, you have to replace those spaces with + (or %20).

你必须用百分号转义保留字符。如果没有别的,您必须用+(或%20)替换这些空格。

Unfortunately, the standard stringByAddingPercentEscapesUsingEncoding is not up to the job, as it leaves some characters unescaped. Your sample doesn't include any of them, but if the person's name was entered as "Bill & Melinda Gates" or "Bill + Melinda Gates", stringByAddingPercentEscapesUsingEncoding would not handle that properly. You really should use CFURLCreateStringByAddingPercentEscapes to percent escape the values, for example using this category:

不幸的是,标准的stringbyadd百分点escape usingencoding不能胜任这项工作,因为它使一些字符无法转义。你的样本中没有包含其中任何一个,但是如果这个人的名字被输入为“比尔和梅林达•盖茨”或“比尔和梅林达•盖茨”,stringbyaddingpercent无法正确处理这个问题。你真的应该使用cfurlcreatestringbyaddpercent转义百分比转义值,例如使用这个类别:

@implementation NSString (URLEncode)

- (NSString *)stringForHTTPRequest
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)self,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

@end

This properly escapes all reserved characters, but replaces spaces with + characters (which you should do if your request type is application/x-www-form-urlencoded).

这将正确地避开所有保留的字符,但是替换带有+字符的空格(如果您的请求类型是应用程序/x-www-form-urlencode,您应该这样做)。

Alternatively, you can also replace the space characters with %20 like so:

或者,也可以将空格字符替换为%20,如下所示:

- (NSString *)stringForHTTPRequest
{
    return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                     (CFStringRef)self,
                                                                     NULL,
                                                                     (CFStringRef)@":/?@!$&'()*+,;=",
                                                                     kCFStringEncodingUTF8));
}

With that, you could modify that line of code that builds the URL string:

这样,您就可以修改构建URL字符串的代码行:

NSString *enquiryurl = [NSString stringWithFormat:@"%@name=%@&phone=%@&email=%@&address=%@&comments=%@&mobile=%@",
                        siteurl, 
                        [name stringForHTTPRequest],
                        [phone stringForHTTPRequest],
                        [email stringForHTTPRequest],
                        [address stringForHTTPRequest],
                        [comments stringForHTTPRequest],
                        [mobile stringForHTTPRequest]];

#3


2  

According the docs, if a NSURL object is initialized with a string, the string must conform to RFC 2396 (see official Apple docs URLWithString).

根据文档,如果一个NSURL对象是用字符串初始化的,那么这个字符串必须符合RFC 2396(参见官方的Apple docs URLWithString)。

The most recent RFC however is RFC 3986 which obsoletes RFC 2396.

最新的RFC是RFC 3986,它将淘汰RFC 2396。

Caution:

Neither Cocoa nor Core Foundation will have a function which out of the box returns a properly encoded URL string conforming to RFC 2396 or RFC 3986, though.

但是,Cocoa和Core Foundation都不会有一个函数,它会返回一个正确编码的URL字符串,该字符串符合RFC 2396或RFC 3986。

Different components of a URL have varying percent encoding requirements.

URL的不同组件有不同百分比的编码需求。

Edit:

编辑:

In order to transmit structured parameters in a unstructured query component of a URL, an encoding scheme equal to the application/x-www-form-urlencoded encoding algorithm can be applied to the query component.

为了在URL的非结构化查询组件中传输结构化参数,可以将与应用程序/x-www-form- urlencoding编码算法相同的编码方案应用到查询组件。

A helper function which encodes the name or value and which conforms to that encoding can be implemented as:

编码名称或值并符合该编码的辅助函数可实现为:

static NSString* urlformdata_encode(NSString* s) {
    CFStringRef charactersToLeaveUnescaped = CFSTR(" ");
    CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@~");

    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                             kCFAllocatorDefault,
                             (__bridge CFStringRef)s,
                             charactersToLeaveUnescaped,
                             legalURLCharactersToBeEscaped,
                             kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

(Note: this code depends on the current implementation of CFURLCreateStringByAddingPercentEscapes, especially its default escaping. If those change, the code may not correctly implement the algorithm.)

(注意:此代码依赖于cfurlcreatestringbyaddingpercent转义的当前实现,特别是它的默认转义。如果这些改变,代码可能不能正确地实现算法)。

According RFC 3986, the query component of the URL is treated as an unstructured percent encoded byte stream containing only ASCII characters.

根据RFC 3986, URL的查询组件被视为只包含ASCII字符的非结构化百分比编码字节流。

Originally, the "application/x-www-form-urlencoded" encoding scheme has been defined for transmitting form-data from a browser to a server which becomes the payload of a body. That is, the context is totally different than for URLs. Nonetheless, even this encoding scheme is not defined in RFC 3986, it is finally compatible with the URL encoding scheme.

最初,“应用/x-www-form- urlen编码”编码方案被定义为将表单数据从浏览器传输到服务器,而服务器将成为一个主体的有效负载。也就是说,上下文与url完全不同。尽管如此,即使这个编码方案在RFC 3986中没有定义,它最终还是与URL编码方案兼容。

Caveats

The "application/x-www-form-urlencoded" encoding scheme may produce percent escapes for characters that are now in the "Unreserved" character set according RFC 3986, namely the tilde ~ character. Characters in the "Unreserved" character set don't need to be escaped. More strictly, due to implications in URI comparison implementations, RFC 3986 makes this recommendation:

“应用/x-www-form- urlencoding”编码方案可能会对RFC 3986中“无保留”字符集中的字符产生百分比转义,也就是tilde ~字符。“无保留”字符集中的字符不需要转义。更严格地说,由于URI比较实现的影响,RFC 3986提出了以下建议:

"For consistency, percent-encoded octets in the ranges of ALPHA (%41-%5A and %61-%7A), DIGIT (%30-%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should not be created by URI producers".

“为了一致性,在ALPHA (%41-%5A和%61-%7A)、位数(%30-%39)、连字符(%2D)、周期(%2E)、下划线(%5F)或倾斜(%7E)范围内的百分比编码的八进制数不应由URI生产者创建”。

In order to not escape the tilde ~ in query parameters, one can remove the tilde ~ from the set of legal URL characters to be escaped legalURLCharactersToBeEscaped:

为了不转义查询参数中的tilde ~,可以从要转义的合法URL字符集合中删除tilde ~:

CFStringRef legalURLCharactersToBeEscaped = CFSTR("!$&'()+,/:;=?@");

Not escaping the tilde should not cause issues, even though it is not strict according the "application/x-www-form-urlencoded encoding" algorithm.

不转义tilde不应该引起问题,即使它不是严格按照“应用/ www-form- urlencoding”算法。

Differences to the other suggested algorithms to this question:

Since the "application/x-www-form-urlencoded" decoding algorithm decodes any percent decoded character sequence into its corresponding Unicode code unit, differences in the set of legalURLCharactersToBeEscaped specified in CFURLCreateStringByAddingPercentEscapes during encoding may eventually yield equal strings.

由于“application/x-www-form- urlencoding”解码算法将任何百分比的解码字符序列解码成相应的Unicode代码单元,所以在编码过程中,cfurlcreatestringbyaddingpercent转义中指定的legalurlcharacterstobeescape集合的差异最终可能会产生相等的字符串。

(Edit: removed helper functions which encode components of a URL, which are not relevant when a query string should be encoded via application/x-www-form-urlencoded)

(编辑:删除用于编码URL组件的助手函数,当查询字符串应该通过application/ www-form- urlencodes编码时,这些函数与此无关)

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/10/09/4ca83130fa5d1dd30e1e187acce2ee14.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告