HTTP-сообщение UIIMAGE и параметров для веб-сервера - PullRequest
2 голосов
/ 11 марта 2011

Я пытаюсь отправить несколько параметров и изображение на веб-сервер из моего проекта iphone.Я считаю, что изображение отправлено нормально, но я не могу получить доступ к другим параметрам.Я не уверен почему?Я считаю, что все сделал правильно

-(void) submitNewWigiItem: (UIImage*) item forUserWithId: (NSString*) wigi_id WithFbId:     (NSString *) fb_id withWigiAccessToken: (NSString *) access_token  withComment: (NSString*)   comment withTag: (NSString*) tag;
{
//setup url
NSURL *wigiURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@%@/items",wigiBaseURL,wigi_id]];


NSData *imageData = UIImageJPEGRepresentation(item, 90);

//setup request for add item
NSMutableURLRequest *wigiRequest = [[[NSMutableURLRequest alloc] initWithURL:wigiURL cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                            timeoutInterval:10] autorelease];
[wigiRequest setHTTPMethod:@"POST"];

NSString *boundary = [[NSString alloc] initWithString: [[NSProcessInfo processInfo] globallyUniqueString]];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[wigiRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];

//add body
NSMutableData *postBody = [NSMutableData data];
//image
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"wigi_item_image\"; filename=\"item.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//facebook id
//  [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"wigi_access_token"] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"123post");
[postBody appendData:[[NSString stringWithFormat:@"%@\r\n", access_token] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//tag
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"wigi_item_tag"] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"123post");
[postBody appendData:[[NSString stringWithFormat:@"%@\r\n", tag] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//comments
[postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"wigi_item_comment"] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"123post");
[postBody appendData:[[NSString stringWithFormat:@"%@\r\n", comment] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[wigiRequest setHTTPBody:postBody];

// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:wigiRequest returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

NSLog(returnString);

Ответы [ 2 ]

5 голосов
/ 14 марта 2011

Я пытался использовать ASIHTTRequest, но не смог правильно импортировать его в свой проект. Поэтому я вернулся к использованию NSURLConnection. Вот код, чтобы заставить его работать, если у кого-то есть похожий вопрос. Есть все еще некоторые проблемы с чтением ответа об ошибке и с сборкой мусора. Вот почему я прокомментировал их сейчас. Если вы решите эти проблемы, пожалуйста, обновите. Спасибо

-(void) submitNewWigiItem:(UIImage *)item 
            forUserWithId:(NSString* )wigi_id 
                 WithFbId:(NSString *)fb_id 
      withWigiAccessToken:(NSString *)access_token  
              withComment:(NSString *)comment 
                  withTag:(NSString *)tag {
    //setup url
    NSURL *wigiURL = [[NSURL alloc] initWithString:[NSString stringWithFormat:@"%@%@/items",wigiBaseURL,wigi_id]];

    NSLog(@"in submitNewWigiItem");
    // create the connection
    NSMutableURLRequest *wigiRequest = [NSMutableURLRequest requestWithURL:wigiURL
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:30.0];

    // change type to POST (default is GET)
    [wigiRequest setHTTPMethod:@"POST"];

    // just some random text that will never occur in the body
    NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";

    // header value
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",
                                stringBoundary];

    // set header
    [wigiRequest addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];

    //add body
    NSMutableData *postBody = [NSMutableData data];
    NSLog(@"body made");
    //wigi access token 
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"wigi_access_token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[access_token dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    //facebook id   
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"wigi_facebook_id\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[fb_id dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    //tag
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"wigi_item_tag\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[tag dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    //comment
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"wigi_item_comment\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[comment dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    //image
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"wigi_item_image\"; filename=\"item.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // get the image data from main bundle directly into NSData object
    NSData *imgData = UIImageJPEGRepresentation(item, 1.0);
    // add it to body
    [postBody appendData:imgData];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        NSLog(@"message added");
    // final boundary
    [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // add body to post
    [wigiRequest setHTTPBody:postBody];

    NSLog(@"body set");
    // pointers to some necessary objects
    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
    NSError* error = [[NSError alloc] init] ;

    // synchronous filling of data from HTTP POST response
    NSData *responseData = [NSURLConnection sendSynchronousRequest:wigiRequest returningResponse:&response error:&error];
    NSLog(@"just sent request");

    if (error) {
        //NSLog(@"EROROROROROROR: %@", error);
    }
    NSLog(@"just 3");

    // convert data into string
    NSString *responseString = [[[NSString alloc] initWithBytes:[responseData bytes]
                                                         length:[responseData length]
                                                       encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"done");
    // see if we get a welcome result
    NSLog(@"%@", responseString);
    /*
    //garbage collection
    [imgData release];
    [wigiURL release];
    [wigiRequest release];
    [stringBoundary release];
    [headerBoundary release];
    */
}
1 голос
/ 11 марта 2011

Этот код ужасно отформатирован, за ним очень трудно следовать.

Возможно, вы захотите взглянуть на ASIHTTPRequest, который значительно упрощает размещение форм, чем все это вручную.

http://allseeing -i.com / ASIHTTPRequest /

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...