如何使用POST从iOS的应用程序发送的NSData?(How send NSData using

2019-06-24 19:32发布

NSData *imageData = UIImagePNGRepresentation(image);

如何使用POST发送的imageData?

Answer 1:

下面的代码应帮助

NSData *imageData = UIImagePNGRepresentation(image);

NSURL *yourURL = ...
NSMutableURLRequest *yourRequest = [NSMutableURLRequest requestWithURL:yourURL 
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy 
                                                       timeoutInterval:60.0];
//Set request to post
[yourRequest setHTTPMethod:@"POST"];

//Set content type 
[yourRequest setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

// Set authorization header if required
...

// set data
[yourRequest setHTTPBody:imageData];


// create connection and set delegate if needed
NSURLConnection *yourConnection = [[NSURLConnection alloc] initWithRequest:yourRequest 
                                                                  delegate:self
                                                          startImmediately:YES];

请注意,假设您正在使用ARC。



Answer 2:

您可以检查这个答案,如果你有好的使用NSURLConnection的https://stackoverflow.com/a/10750428/591951

这篇文章介绍了如何发布音频文件,但你可以用同样的方法上传任何文件



Answer 3:

您可以使用ASIHTTPRequest库: http://allseeing-i.com/ASIHTTPRequest/

然后,它是很容易:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

// Upload an NSData instance
[request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];

关于如何使用信息: http://allseeing-i.com/ASIHTTPRequest/How-to-use



文章来源: How send NSData using POST from a iOS application?
标签: ios post nsdata