从iPhone向Ruby on Rails(RoR)服务器发送多部分请求 [英] Sending multipart request from iPhone to Ruby on Rails (RoR) server

查看:53
本文介绍了从iPhone向Ruby on Rails(RoR)服务器发送多部分请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了这个问题,发现了类似的问题,但没有一个喜欢它.

I've searched for this issue and found similar problems but none like it.

我正在手动建立请求

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:TEST_URL]];
[request setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request addValue:contentType forHTTPHeaderField:@"Content-Type"];

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=upload[jsondata]\r\n\n Content-Type: application/octet-stream\r\n\r\n", [dateFormatter stringFromDate:startDate]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[json dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

此请求到达Rails服务器时,可以理解Content-Disposition,Content-Type,但是主体的JSON部分被捕获为"ActionDispatch :: Http :: UploadedFile",这意味着服务器无法理解JSON.并正在将其视为文件.

When this request reaches the rails server, it understands Content-Disposition, Content-Type, but the JSON part of the body is captured as "ActionDispatch::Http::UploadedFile", meaning the server isn't understanding the JSON and is looking at it as if it was a file.

我做错了什么?从iOS设备发出并发送到Rails服务器的请求是否存在问题?某种错误?我已经尝试过ASIHTTPRequest,结果相同.

What am I doing wrong? Is this a problem with requests made from iOS devices and sent to Rails servers? Some sort of bug? I've already tried ASIHTTPRequest, with the same results.

推荐答案

我用非常简单的方法解决了这个问题.我必须删除

I solved the problem with something incredibly simple. I had to remove

Content-Type: application/octet-stream

从正文开始,我必须向请求添加Connection:Keep-Alive,如下所示:

from the body and I had to add Connection: Keep-Alive to the request, like this:

[request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];

在使用WireShark在接收计算机上侦听请求并注意到连接被设置为默认关闭后,我尝试了它.

I tried it after listening to the request on the receiving computer using WireShark and noticing that the connection was set to close as default.

这篇关于从iPhone向Ruby on Rails(RoR)服务器发送多部分请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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