我正在寻求从iPhone SDK调用HTTP_POST到我服务器上的php文件。如果我在下面打电话:
NSMutableDictionary *requestDictionary = [NSMutableDictionary dictionary];
[requestDictionary setObject:@"testvalue" forKey:@"test"];
[requestDictionary setObject:@"test2value" forKey:@"test2"];
[requestDictionary setObject:@"test3value" forKey:@"test3"];
NSString *jsonString = [requestDictionary JSONRepresentation];
NSString *urlString = @"http://www.example.org";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:CONNECTION_TIMEOUT];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString length]];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: requestData];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
我是否应该像这样接收这样的帖子数据(在php中):
echo "Hello";
if(isset($_POST['test']))
{
echo $_POST['test'];
}
编辑:
要测试,在我的connectionDidFinishLoading
我只是记录整个回复
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *responseString = [[NSString alloc] initWithData:dataRecieved encoding:NSASCIIStringEncoding];
[dataRecieved release];
NSLog(@"Response: %@", responseString);
}
我在寻找帖子之前得到了回应,但没有别的。有谁知道我哪里出错了?
答案 0 :(得分:2)
您的请求正文是JSON值,但您的服务器需要application/x-www-form-urlencoded
个编码字段。
您可以将字典转换为具有以下类别的编码字段。
@interface NSDictionary (FormData)
- (NSString*) formUrlEncodedData;
@end
@implementation NSDictionary (FormData)
- (NSString*) formUrlEncodedData
{
NSString *result = nil;
for( NSString *k in [self keyEnumerator]) {
if (![result isEqual:@""]) {
result = [result stringByAppendingString:@"&"];
}
result = [result stringByAppendingString:[k stringByUrlEncoding]];
result = [result stringByAppendingString:@"="];
NSString *v = [self objectForKey:k];
result = [result stringByAppendingString:[v stringByUrlEncoding]];
}
return result;
}
@end
其中stringByUrlEncoding由NSString上的类别提供,我从Cocoanetics采购。
@interface NSString (Helpers)
- (NSString*) stringByUrlEncoding;
@end
@implementation NSString (UrlEncoding)
- (NSString*) stringByUrlEncoding
{
return (NSString*)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
}
@end
答案 1 :(得分:0)
您将在NSURLConnection委托方法中获得回复。一旦得到响应,您可以使用NSXMLParser来解析它并获取所需的字段。如果您需要其他相关信息,请与我们联系。将尝试发布一些相关的代码。
答案 2 :(得分:0)
如果我可以给你一个建议。检查Facebook IOS SDK的源代码。 这是学习新技术的好方法。