IOS HTTP Post创建和处理响应

时间:2014-09-15 15:57:15

标签: ios http nsurlconnection nsurlrequest

我试图重构我在Phonegap Javascript中使用的一些代码,这些代码正在将音频文件上传到IOS Objective C而我有点迷失。

JavaScript中的代码如下:

function uploadToClypit(file){
    console.log(file);

    var options = new FileUploadOptions();
    options.name = file.fullPath.substr(file.fullPath.lastIndexOf('/')+ 1);
    options.audioFile = file.nativeURL;
    options.fileName = file.nativeURL;
    options.mimeType = "audio/wav";
    options.headers = {
        Connection: "close"
    }
    options.chunkedMode = false;
    console.log(options);

    var ft = new FileTransfer();
    console.log(file.nativeURL);
    ft.upload(file.nativeURL, encodeURI("http://upload.clyp.it/upload"), win, failUpload, options);

}

响应的处理如下:

var win = function(r){
    var jsontext = r.response;
    var json = JSON.parse(jsontext);
    console.log(json);

}

所以在IOS中我尝试创建HTTP Post请求,将音频文件附加到HTTP Body,发送一些其他文本参数然后处理响应。

到目前为止我已经完成了这件事。

  1. 设置我的控制器以实现
  2. 设置NSMutableData变量* _responseData以保存响应
  3. 我通过执行以下操作来创建HTTP请求:

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                        initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://upload.clyp.it/upload"]]];
    
        [request setHTTPMethod:@"POST"];
    
        NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
        NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
        [request addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];
    
         NSMutableData *postBody = [NSMutableData data];
    
        [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
        [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file upload\"; filename=\"uploadaudio.mp3\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [postBody appendData:[@"Content-Type: audio/m4a\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
        NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    
    
    
    
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:cellIndexPath];
        ICIRecordingCell *c = (ICIRecordingCell *)cell;
        NSString *fileName = c.title.text;
        NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];
    
        NSData *audioData;
    
        audioData = [[NSData alloc] initWithContentsOfFile:filePath];
        [postBody appendData:audioData];
         [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
         [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    
        [request setHTTPBody:postBody];
        [[NSURLConnection alloc] initWithRequest:request delegate:self];
    

    然后我尝试设置委托方法来处理响应:

        #pragma mark NSURLConnection Delegate Methods
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
        // A response has been received, this is where we initialize the instance var you created
        // so that we can append data to it in the didReceiveData method
        // Furthermore, this method is called each time there is a redirect so reinitializing it
        // also serves to clear it
        _responseData = [[NSMutableData alloc] init];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        // Append the new data to the instance variable you declared
        [_responseData appendData:data];
    }
    
    - (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                      willCacheResponse:(NSCachedURLResponse*)cachedResponse {
        // Return nil to indicate not necessary to store a cached response for this connection
        return nil;
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        // The request is complete and data has been received
        // You can parse the stuff in your instance variable now
        NSString *d = (NSString *)_responseData;
        NSLog(d);
    
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        // The request has failed for some reason!
        // Check the error var
    }
    

    当我查看_responseData中返回的内容时,我不确定该怎么做>

      

    打印自我> _responseData的描述:< 7b224d65 73736167   65223a22 416e2065 72726f72 20686173 206f6363 75727265 642e227d>

    我也不确定我是否正确设置了请求 - 我刚刚借用了我在StackOverflow上找到的代码而未完全理解它。

    任何指针方向都超过欢迎

0 个答案:

没有答案