使用NSOutputStream来POST到url [英] Using NSOutputStream to POST to url

查看:210
本文介绍了使用NSOutputStream来POST到url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想做的是发送一个POST请求到一个url。现在我尝试使用NSURLRequest / NSURLConnection,但是有问题,并决定移动到较低的水平,也是因为我想发送大文件,并认为直接处理流可能更好。但是输出流委托似乎从未被调用,我似乎不能使用NSOutputStream的 initWithURL 找到示例。

So all I want to do is send a POST request to a url. Now I tried using NSURLRequest/NSURLConnection, but was having problems with that and decided to move to a lower level, also because I want to send large files and thought dealing directly with streams might be better. But the output stream delegate never seems to be called, and I can't seem to find examples using NSOutputStream's initWithURL.

NSURL *url = [NSURL URLWithString:NSString stringWithFormat: @"http://url"];
self.outputStream = [[NSOutputStream alloc] initWithURL:url append:NO];
[outputStream retain];
[outputStream setDelegate:self];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream open];

看起来outputStream在init之后是空的,我不能理解,因为我的url是一个有效的网址 - 我可以从终端ping它,并从其他来源发送数据。我做错了,或者任何人可以告诉我如何使用流写入一个POST请求到URL?感谢。

It seems that the outputStream is null after the init, which I can't understand because my url is a valid url--I can ping it from the terminal and send data from other sources. Am I doing something wrong, or can anyone tell me how to write a POST request to a URL using streams? Thanks.

推荐答案

您不能使用 NSOutputStream 一个HTTP服务器。

You cannot use NSOutputStream to send a POST request to a HTTP server.

好的方法是创建一个 NSMutableURLRequest ,并提供一个 HTTPBodyStream ,然后创建一个 NSURLConnection 发送请求。

The good method is to create a NSMutableURLRequest and provide that request with a HTTPBodyStream then create a NSURLConnection to send the request.

c $ c> HTTPBodyStream 是一个 NSInputStream 请求将读取正文。您可以使用 NSData 对象或一个文件的内容来初始化它。

The HTTPBodyStream is an NSInputStream the request will read the body from. You may initialize it with a NSData object or with the contents of a file.

如果要提供自定义内容(例如,您要将文件作为 multipart / form-data 请求的一部分上传),您可能需要将 NSInputStream 。在这种情况下,我建议您查看如何实现CoreFoundation免费桥接NSInputStream子类,它解释了如何解决使用 NSURLConnection 。或者您可以使用 ASIHTTPRequest 提供开箱即用的多部分HTTP请求。

If you want to provide a custom content (for example, you want to upload a file as part of a multipart/form-data request), you may need to subclass NSInputStream. In such case, I suggest you to have a look at How to implement CoreFoundation toll-free bridged NSInputStream subclass, which explains how to address an issue that occurs when using custom input streams with NSURLConnection. Or you may use ASIHTTPRequest which provides multipart HTTP requests out of the box.

这篇关于使用NSOutputStream来POST到url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆