直接在ASIFormDataRequest中的多部分POST请求

时间:2012-06-26 18:34:46

标签: cocoa post asiformdatarequest

所以你认为找到ASIFormDataRequest的POST信息的直接例子很容易,但我还没有找到这些格式的1:1。这是我要发送的POST请求:

POST /fileXfer HTTP/1.1
Content-Type: multipart/form-data; boundary=AaB03x
Content-Length: 200
AppID:myID
TransferID:abcd1234

-- AaB03x
Content-Disposition: form-data; name="data"; filename="xxx"
Content-Type: application/octet-stream
Content-Length: 100

... contents of file ...

--AaB03x--

编辑:

事实证明,接收数据的服务器存在问题。但这就是我最终的结果!

NSURL *url = [NSURL URLWithString:@"http://IP:PORT/fileXfer"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostFormat:ASIMultipartFormDataPostFormat];

//Sets headers of POST
[request addRequestHeader:@"X-Application-Id" value:@"myID"];
[request addRequestHeader:@"X-Transfer-Id" value:@"abcd1234"];

//Sets data
NSData *fileData = [NSData dataWithContentsOfFile:kEncryptedFilePath];
[request setData:fileData withFileName:@"xxx" andContentType:@"application/octet-stream" forKey:@"data"];

[request setDelegate:self];
[request startAsynchronous];

我还在ASIFormDataRequest的buildMultipartFormDataPostBody中添加了以下行,其中设置了Content-Disposition和Content-Type:

[self appendPostString:[NSString stringWithFormat:@"Content-Length: %lu\r\n\r\n", [data length]]];`

我不确定是否有更简单的方法直接从请求添加该行,但是在我尝试过的事情中,这似乎是有效的。

1 个答案:

答案 0 :(得分:0)

您可以更好地使用ASIFormDataRequest提供的方法,而不是手动构建可能导致错误的HTTP正文。

NSURL *url = [NSURL URLWithString:@"http://IP:PORT/fileXfer"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

[request addRequestHeader:@"X-Application-Id" value:@"myID"];
[request addRequestHeader:@"X-Transfer-Id" value:@"abcd1234"];

[request setData:[self fileData] withFileName:@"xxx" andContentType:@"application/octet-stream" forKey:@"data"];

[request setDelegate:self];
[request startAsynchronous];