NSURLConnection连接到服务器,但不发布数据 [英] NSURLConnection connecting to server, but not posting data
问题描述
每当我尝试向PHP服务器发布内容时,都会收到以下消息。似乎代码连接到服务器,但没有返回数据,并且后期数据不会通过。它通过我制作的Java应用程序工作,所以我可以保证他们的PHP没有错。如果您可以帮助我,或者需要更多代码来帮助我,那就请求它。谢谢。
Whenever I attempt to post something to my PHP Server, I receive the following message. It seems as if the code is connecting to the server, but no data is returned, and the post data isn't going through. It worked through a Java App that I made, so I can assure that their is nothing wrong with my PHP. If you could help me, or need any more code to help me, just ask for it. Thanks.
以下是为NSURLConnection准备变量的代码:
Here is the code that prepares my variables for the NSURLConnection:
NSString *phash = [NSString stringWithFormat:@"%d",phashnum];
[phash stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
name = _nameField.text;
[name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
email = _emailField.text;
[email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
以下是我的NSURLConnection的代码:
Here is the code for my NSURLConnection:
NSString *urlPath = [NSString stringWithFormat:@"http://54.221.224.251"];
NSURL *url = [NSURL URLWithString:urlPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *stringdata = [NSString stringWithFormat:@"name=%@&email=%@&phash=%@",name,email,phash];
NSOperationQueue *queue= [[NSOperationQueue alloc]init];
NSString *postData = [[NSString alloc] initWithString:stringdata];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if ([data length] > 0 && connectionError==nil){
NSLog(@"Connection Success. Data Returned");
NSLog(@"Data = %@",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if([data length] == 0 && connectionError == nil){
NSLog(@"Connection Success. No Data returned.");
NSLog(@"Connection Success. Data Returned");
NSLog(@"Data = %@",data);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if(connectionError != nil && connectionError.code == NSURLErrorTimedOut){
NSLog(@"Connection Failed. Timed Out");
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
else if(connectionError != nil)
{
NSLog(@"%@",connectionError);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int code = [httpResponse statusCode];
NSString *coder = [NSString stringWithFormat:@"%d",code];
NSLog(@"%@",coder);
}
}];
提前致谢。
推荐答案
正如@elk所说,你应该用 +
替换空格。但是您应该对保留字符进行百分比编码(如 RFC2396 中所定义)。
As @elk said, you should replace spaces with +
. But you should percent-encode reserved characters (as defined in RFC2396).
不幸的是,标准的 stringByAddingPercentEscapesUsingEncoding
并没有逃脱所有保留字符的百分比。例如,如果名称是Bill& Melinda Gates或Bill + Melinda Gates,则 stringByAddingPercentEscapesUsingEncoding
不会逃脱&
或 +
(因此 +
将被解释为空格,并且&
会被解释为分隔下一个 POST
参数。)
Unfortunately, the standard stringByAddingPercentEscapesUsingEncoding
does not percent escape all of the reserved characters. For example, if the name was "Bill & Melinda Gates" or "Bill + Melinda Gates", stringByAddingPercentEscapesUsingEncoding
would not percent escape the &
or the +
(and thus the +
would have been interpreted as a space, and the &
would have been interpreted as delimiting the next POST
parameter).
相反,请使用 CFURLCreateStringByAddingPercentEscapes
,在 legalURLCharactersToBeEscaped
参数然后用 +
替换空格。例如,您可以定义 NSString
类别:
Instead, use CFURLCreateStringByAddingPercentEscapes
, supplying the necessary reserved characters in the legalURLCharactersToBeEscaped
parameter and then replace the spaces with +
. For example, you might define a NSString
category:
@implementation NSString (PercentEscape)
- (NSString *)stringForPostParameterValue:(NSStringEncoding)encoding
{
NSString *string = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
(CFStringRef)@" ",
(CFStringRef)@";/?:@&=+$,",
CFStringConvertNSStringEncodingToEncoding(encoding)));
return [string stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}
@end
注意,我主要关心的是使用&
和 +
,字符,但 RFC2396 (取代RFC1738)将这些附加字符列为保留字符,因此在中包含所有这些保留字符可能是谨慎的。 legalURLCharactersToBeEscaped
。
Note, I was primarily concerned with the &
and +
, characters, but RFC2396 (which supersedes RFC1738) listed those additional characters as being reserved, so it's probably prudent to include all of those reserved characters in the legalURLCharactersToBeEscaped
.
将这一点拉到一起,我可能会将请求发布为:
Pulling this together, I might have code that posts the request as:
NSDictionary *params = @{@"name" : _nameField.text ?: @"",
@"email": _emailField.text ?: @"",
@"phash": [NSString stringWithFormat:@"%d",phashnum]};
NSURL *url = [NSURL URLWithString:kBaseURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[self httpBodyForParamsDictionary:params]];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error)
NSLog(@"sendAsynchronousRequest error = %@", error);
if (data) {
// do whatever you want with the data
}
}];
使用实用程序方法:
- (NSData *)httpBodyForParamsDictionary:(NSDictionary *)paramDictionary
{
NSMutableArray *paramArray = [NSMutableArray array];
[paramDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
NSString *param = [NSString stringWithFormat:@"%@=%@", key, [obj stringForPostParameterValue:NSUTF8StringEncoding]];
[paramArray addObject:param];
}];
NSString *string = [paramArray componentsJoinedByString:@"&"];
return [string dataUsingEncoding:NSUTF8StringEncoding];
}
这篇关于NSURLConnection连接到服务器,但不发布数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!