我正在向服务器NSMutableURLRequest
发送请求,如下所示,该问题之一是电话号码并带有“+”号,该问题已消除。
// Create the request.
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:myURL ]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
/**
add post
****/
[theRequest setHTTPMethod:@"POST"];
NSString *encodedfullNumberFinal= [ fullNumberFinal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *append2URL=[NSString stringWithFormat:@"deviceType=%d&token=%@&mobileNumber=%@&code=%@",
1, token,
encodedfullNumberFinal
,myBid
];
[theRequest setHTTPBody:[append2URL
dataUsingEncoding:NSUTF8StringEncoding /*NSUnicodeStringEncoding*/]];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = /*[*/[NSMutableData data] /* retain]*/;
} else {
// Inform the user that the connection failed.
}
注意,表单服务器端我正在使用Tomcat和Java。
任何建议如何保留带有“+”号的参数?
最佳答案
问题在于标准stringByAddingPercentEscapesUsingEncoding
对加号不起作用。不过,Core Foundation的CFURLCreateStringByAddingPercentEscapes
可为您提供更多控制权。我使用的NSString
类别提供了CFURLCreateStringByAddingPercentEscapes
的简单接口:
@implementation NSString (UrlEncode)
+ (NSString *)stringByAddingPercentEscapesFor:(NSString *)string
legalURLCharactersToBeEscaped:(NSString *)legalURLCharactersToBeEscaped
usingEncoding:(NSStringEncoding)encoding
{
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
NULL,
(CFStringRef)legalURLCharactersToBeEscaped,
CFStringConvertNSStringEncodingToEncoding(encoding)
));
}
- (NSString *)stringByAddingPercentEscapesFor:(NSString *)legalURLCharactersToBeEscaped
usingEncoding:(NSStringEncoding)encoding
{
return [NSString stringByAddingPercentEscapesFor:self
legalURLCharactersToBeEscaped:legalURLCharactersToBeEscaped
usingEncoding:encoding];
}
- (NSString *)stringByAddingPercentEscapesForURLParameterUsingEncoding:(NSStringEncoding)encoding
{
return [NSString stringByAddingPercentEscapesFor:self
legalURLCharactersToBeEscaped:@":/?@!$&'()*+,;="
usingEncoding:encoding];
}
@end
然后,我可以使用
stringByAddingPercentEscapesForURLParameterUsingEncoding
而不是stringByAddingPercentEscapesUsingEncoding
,并且加号也将被转义。