Я нашел много полезных советов по стекопереработке о настройке HTTP POST-запроса к моему серверу. Я последовал много примеров. Я настроил быстрый тест в проекте, чтобы попытаться отправить запрос POST и получить некоторые данные с сервера. Вот мой код из ViewController.h У меня есть настройки:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UILabel *label;
NSString *moviePost;
NSMutableData *httpResponse;
NSURLConnection *connection;
}
@property (nonatomic, retain) NSString *moviePost;
@property (nonatomic, retain) NSURLConnection *connection;
@end
И код из моего ViewController.m
#import "ViewController.h"
#import <YAJLiOS/YAJL.h>
@implementation ViewController
@synthesize moviePost;
@synthesize connection;
- (void) viewDidLoad {
[super viewDidLoad];
NSArray *fields = [[NSArray alloc] initWithObjects:@"rating",@"genre",@"plotoutline",@"runtime",@"director",@"writer",@"mpaa",@"year",@"studio", nil];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:
fields,@"fields",
nil];
[fields release];
NSDictionary *tempPost = [[NSDictionary alloc] initWithObjectsAndKeys:
@"2.0", @"jsonrpc",
@"VideoLibrary.GetMovies", @"method",
@"1", @"id",
params, @"params",
nil];
[params release];
moviePost = [tempPost yajl_JSONString];
[tempPost release];
NSLog(@"Going to post: %@\n\n", moviePost);
NSString *url = [NSString stringWithFormat:@"http://192.168.1.133:8080/jsonrpc"];
NSMutableString* requestURL = [[NSMutableString alloc] init];
[requestURL appendString:url];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];
NSData *requestData = [NSData dataWithBytes: [moviePost UTF8String] length: [moviePost length]];
[request setHTTPMethod: @"POST"];
[request setValue:@"text/plain" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: requestData];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[httpResponse setLength:0];
}
// Called when data has been received
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[httpResponse appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString* responseString = [[NSString alloc] initWithData:httpResponse encoding:NSUTF8StringEncoding];
// Do something with the response
NSLog(@"Response: %@", responseString);
[responseString release];
[connection release];
[httpResponse release];
}
- (void)dealloc {
[moviePost release];
[super dealloc];
}
Большая часть кода взята из примеров, которые я нашел. Он работает для отправки запроса POST на сервер, и сервер отвечает с данными. Я доказал это, выполнив захват пакета между тестовым устройством и сервером. Правильный запрос отправляется и правильный ответ отправляется обратно. У меня не возникает проблем при запуске приложения. Я пробежал через анализатор и не получил никаких проблем.
Проблема в том, что я не могу получить ответ на печать в NSLog. когда
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
запускает, показывает строку Response:
в NSLog, но это все, что я получаю.
Есть что-то, чего мне не хватает? Я новичок в объективе-C и XCode. Любая помощь приветствуется.