在objective C中复制http post

2024-04-20 11:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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);

如何发送一个httppost请求,以便它将与上面的html页面相同的数据发送到我的服务器?你知道吗


Tags: nameformdatarequestcontentfilenamestrboundary