使用HTTP Post发送和接收字符串

时间:2011-11-07 19:46:57

标签: objective-c http

我是Objective-C的新手,我在应用程序中工作,我需要使用HTTP Post连接到Java的servlet。

我通过互联网搜索并发现了许多与NSMutableURLRequest NSURLConnection相关的信息。 我做了一些测试,现在我可以发送和接收字符串,但我需要做一些更改,我不知道该怎么做。

我想使用String(已完成)向我的Servlet发送消息,我想停止执行,直到从Servlet收到响应(这是我的问题)。我不能停止执行,我不知道该怎么做。

这是我的代码:

- (NSString *)sendPostRequest: (NSString*)stringToSend {

//URL en formato String
NSString *urlString = @"http://192.168.1.1:8080/Servlet/ListenerServlet";

//Armo el Body con los Datos a enviar
NSMutableString* requestBody = [[NSMutableString alloc] init];
[requestBody appendString:stringToSend]; 

//Creo el Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

//Creo el Objecto con la URL dentro
NSURL *url = [NSURL URLWithString: [NSString stringWithString:urlString]];

//Seteo la URL al Request
[request setURL:url];

//Armo los Datos a Enviar
NSString* requestBodyString = [NSString stringWithString:requestBody];
NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];

//Seteo el Metodo de Envio
[request setHTTPMethod: @"POST"];

//Seteo los Datos a Enviar
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody: requestData];

//Creo la Conexion y automaticamente se envia
[[NSURLConnection alloc] initWithRequest:request delegate:self];

[requestBody release];  
[request release];  

return @"";
}

有人能帮助我吗?

谢谢,抱歉我的英语不好

2 个答案:

答案 0 :(得分:1)

您尝试以同步方式使用异步api(NS​​URLRequest)。 NSURLRequest使用委托模式在后台工作。您启动一个请求,当数据可用或连接完成时,请求会在其委托上调用委托方法。

您应该重新设计您的应用,以便它能够以这种方式工作。网络操作可能需要很长时间,除非必须,否则不应该为用户暂停。

如果你必须停止你的应用程序直到网络操作完成,你应该设置某种停用/恢复功能来禁用你的UI,而不是占用主线程。

jbat100建议ASIHTTPRequest。它可能是矫枉过正的,也是异步的,并且被它的作者遗弃了。我想说如果你需要使用网络库,你应该看看AFNetworking。同样,可能是过度杀伤,绝对异步,但主动维护并使用基于块的界面。

答案 1 :(得分:1)

最后,我使用NSMutableURLRequest和NSURLConnection与sendSynchronousRequest一起工作。

这是使用的代码:

- (NSString*) sendPostRequest:(NSString *)stringToSend{

NSString *urlString = [self serverURL];

NSURL *url = [NSURL URLWithString: urlString];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"POST"];

//set headers

[request addValue:@"Content-Type" forHTTPHeaderField:@"application/x-www-form-urlencoded"];

[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[stringToSend dataUsingEncoding:NSASCIIStringEncoding]];

[request setTimeoutInterval:90]; // set timeout for 90 seconds

NSURLResponse **response = NULL;

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:response error:nil];

NSString *responseDataString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

NSLog(@"Response %@", responseDataString);

return responseDataString;

}

相关问题