复制目标C中的http帖子

时间:2014-10-31 04:27:43

标签: python html ios objective-c http

我的python服务器上有这个基本的html文件

<HTML><BODY>

<form method='POST' enctype='multipart/form-data' action='http://127.0.0.1:8007/'>

File to upload: <input type=file name=upfile ><br>

<br>
<input type=submit value=Press> to upload the file!
</form>

</BODY>
</HTML>

我想在Objective C中做同样的帖子。我试过这个

NSString *str=[[NSBundle mainBundle] pathForResource:@"houseme" ofType:@"jpg"];
    NSData *fileData = [NSData dataWithContentsOfFile:str];
    NSLog(@"\n\nthe string %@",str);

    NSString *urlString = @"http://localhost:8007";
    NSString *filename = @"houseme";
    request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    //NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *boundary = [NSString stringWithFormat:@"%d",[fileData length]];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; upfile=\"claraisadalek\" filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Disposition: attachment; name=\"userfile\"; filename=\".jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:fileData]];
    [postbody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];


    [request setHTTPBody:postbody];



    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);

如何发送HTTP POST请求,以便它将相同的数据发送到我的服务器上面的html页面?

1 个答案:

答案 0 :(得分:0)

请参阅此问题的answer

正如Rob提到的那样,使用AFNetworking要容易得多,我也强烈建议这样做(见链接答案的底部)。

相关问题