2009-07-27 2 views
2

「Twitpic api」を使用して画像をTwitterにアップロードするソースコードを知っている人は、画像をアップロードしようとしているときに、Twitpic APIで画像をアップロードするときの応答コードが正しくありません

は、ここに私のコードです:

- (BOOL)uploadImageToTwitpic:(UIImage*)image 
       withMessage:(NSString*)theMessage 
        username:(NSString*)username 
        password:(NSString*)password 
{ 
    NSString *stringBoundary, *contentType, *message, *baseURLString, *urlString; 
    NSData *imageData; 
    NSURL *url; 
    NSMutableURLRequest *urlRequest; 
    NSMutableData *postBody; 

    // Create POST request from message, imageData, username and password 
    baseURLString = kTwitpicUploadURL; 
    urlString = [NSString stringWithFormat:@"%@", baseURLString]; 
    url = [NSURL URLWithString:urlString]; 
    urlRequest = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; 
    [urlRequest setHTTPMethod:@"POST"]; 

    // Set the params 
    message = ([theMessage length] > 1) ? theMessage : @"Here's my new Light Table collage."; 
    imageData = UIImageJPEGRepresentation(image, kTwitpicImageJPEGCompression); 

    // Setup POST body 
    stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"]; 
    contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; 
    [urlRequest addValue:contentType forHTTPHeaderField:@"Content-Type"]; 

    // Setting up the POST request's multipart/form-data body 
    postBody = [NSMutableData data]; 
    [postBody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"source\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithString:@"lighttable"] dataUsingEncoding:NSUTF8StringEncoding]]; // So Light Table show up as source in Twitter post 

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

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

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

    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media\"; filename=\"%@\"\r\n", @"lighttable_twitpic_image.jpg" ] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:[[NSString stringWithString:@"Content-Type: image/jpg\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; // jpeg as data 
    [postBody appendData:[[NSString stringWithString:@"Content-Transfer-Encoding: binary\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:imageData]; // Tack on the imageData to the end 

    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 
    [urlRequest setHTTPBody:postBody]; 
    NSLog(@"data=======>%@",postBody); 
    NSLog(@"URLReq========>%@",urlRequest); 
    // Spawn a new thread so the UI isn't blocked while we're uploading the image 
    [NSThread detachNewThreadSelector:@selector(uploadingDataWithURLRequest:) toTarget:self withObject:urlRequest]; 

    return YES; // TODO: Should raise exception on error 
} 

- (void)uploadingDataWithURLRequest:(NSURLRequest*)urlRequest { 
    // Called on a separate thread; upload and handle server response 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    [urlRequest retain]; // Retain since we autoreleased it before 

    // Send the request 
    NSHTTPURLResponse *urlResponse; 
    NSError *error; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest 
               returningResponse:&urlResponse 
                  error:&error]; 
    NSString *responseString = [[NSString alloc] initWithData:responseData 
                encoding:NSUTF8StringEncoding]; 

    // Handle the error or success 
    // If error, create error message and throw up UIAlertView 
    NSLog(@"Response Code: %d", [urlResponse statusCode]); 
    if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) { 
     NSLog(@"urlResultString: %@", responseString); 

     NSString *match = [responseString stringByMatching:@"http[a-zA-Z0-9.:/]*"]; // Match the URL for the twitpic.com post 
     NSLog(@"match: %@", match); 

     // Send back notice to delegate 
     [delegate twitpicEngine:self didUploadImageWithResponse:match]; 
    } 
    else { 
     NSLog(@"Error while uploading, got 400 error back or no response at all: %@", [urlResponse statusCode]); 
     [delegate twitpicEngine:self didUploadImageWithResponse:nil]; // Nil should mean "upload failed" to the delegate 
    } 

    [pool drain]; 
    [responseString release]; 
    [urlRequest release]; 
} 
+0

あなたの質問に書式を設定してください。 – Sauron

+0

フォーマットされ、彼のためにそれを再評価しました。 –

答えて

1

編集:私はPOSTリクエストを作成するための別の方法が役立ちますかどうかを確認するためにthis SO questionを読んでお勧め


は、私は自分自身をTwitpic APIに慣れていないんだけど、私はあなたが問題を絞り込むことができますいくつかの提案をしようよ。

最初にチェックするのは、POST本体の正確さです。そのコードを作成するためのコードは、不必要に複雑で読みにくいので、バグがあると驚くことはありません。私は、作成を簡素化し、パフォーマンスを向上させる改訂版(免責事項、私はそれをコンパイルしていない)を投稿しています。 (オートレリースされたNSStringオブジェクトとNSDataオブジェクトのTONを作成し、データバイトを追加するたびに文字列をデータに変換していました)変更可能な文字列を作成して一度変換する方がはるかに簡単で簡単です。すべての変数がメソッドの先頭に宣言されると、コードを読み取るのが少し難しくなります。 C(または派生した言語)の最近の標準ではこれは不要で、最初に変数を宣言することをお勧めします。コードを読みやすくするだけでなく、一般的にいくつかの不要な行を削除します。

ここにはいくつかの推奨改訂版のコードがあります。問題を特定するのが簡単になる場合があります。

- (BOOL)uploadImageToTwitpic:(UIImage*)image 
       withMessage:(NSString*)theMessage 
        username:(NSString*)username 
        password:(NSString*)password 
{ 
    // Create POST request from message, imageData, username and password 
    NSString *baseURLString = kTwitpicUploadURL; 
    NSString *urlString = [NSString stringWithFormat:@"%@", baseURLString]; 
    NSURL *url = [NSURL URLWithString:urlString]; 
    NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] initWithURL:url] autorelease]; 
    [urlRequest setHTTPMethod:@"POST"]; 

    // Set the params 
    NSString *message = ([theMessage length] > 1) ? theMessage : @"Here's my new Light Table collage."; 

    // Setup POST body 
    NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"]; 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", stringBoundary]; 
    [urlRequest addValue:contentType forHTTPHeaderField:@"Content-Type"]; 

    NSString *stringBoundarySeparator = [NSString stringWithFormat:@"\r\n--%@\r\n", stringBoundary]; 

    NSMutableString *postString = [NSMutableString string]; 
    [postString appendString:@"\r\n"]; 
    [postString appendString:stringBoundarySeparator]; 
    [postString appendString:@"Content-Disposition: form-data; name=\"source\"\r\n\r\n"]; 
    [postString appendString:@"lighttable"]; // So Light Table shows up as source in Twitter 
    [postString appendString:stringBoundarySeparator]; 
    [postString appendStringWithFormat:@"Content-Disposition: form-data; name=\"username\"\r\n\r\n%@", username]; 
    [postString appendString:stringBoundarySeparator]; 
    [postString appendStringWithFormat:@"Content-Disposition: form-data; name=\"password\"\r\n\r\n%@", password]; 
    [postString appendString:stringBoundarySeparator]; 
    [postString appendStringWithFormat:@"Content-Disposition: form-data; name=\"message\"\r\n\r\n%@", message]; 
    [postString appendString:stringBoundarySeparator]; 
    [postString appendStringWithFormat:@"Content-Disposition: form-data; name=\"media\"; filename=\"%@\"\r\n", @"lighttable_twitpic_image.jpg"]; 
    [postString appendString:@"Content-Type: image/jpg\r\n"]; // data as JPEG 
    [postString appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"]; 

    // Setting up the POST request's multipart/form-data body 
    NSMutableData *postBody = [NSMutableData data]; 
    [postBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postBody appendData:UIImageJPEGRepresentation(image, kTwitpicImageJPEGCompression)]; // Tack on the image data to the end 
    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; 

    [urlRequest setHTTPBody:postBody]; 
    NSLog(@"data=======>%@",postBody); 
    NSLog(@"URLReq========>%@",urlRequest); 
    // Spawn a new thread so the UI isn't blocked while we're uploading the image 
    [NSThread detachNewThreadSelector:@selector(uploadingDataWithURLRequest:) toTarget:self withObject:urlRequest]; 

    return YES; // TODO: Should raise exception on error 
} 

// Called on a separate thread; upload and handle server response 
- (void)uploadingDataWithURLRequest:(NSURLRequest *)urlRequest { 
    [urlRequest retain]; // Retain since we're using it in this method 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // Send the request 
    NSHTTPURLResponse *urlResponse; 
    NSError *error; 
    NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest 
               returningResponse:&urlResponse 
                  error:&error]; 
    NSString *responseString = [[[NSString alloc] initWithData:responseData 
                 encoding:NSUTF8StringEncoding] autorelease]; 

    // Handle the error or success 
    // If error, create error message and throw up UIAlertView 
    NSLog(@"Response Code: %d", [urlResponse statusCode]); 
    NSLog(@"Response String: %@", responseString); 
    if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) { 
     NSString *match = [responseString stringByMatching:@"http[a-zA-Z0-9.:/]*"]; // Match the URL for the twitpic.com post 
     NSLog(@"match: %@", match); 
     // Send back notice to delegate 
     [delegate twitpicEngine:self didUploadImageWithResponse:match]; 
    } 
    else { 
     NSLog(@"Error while uploading, got 400 error back or no response at all: %@", [urlResponse statusCode]); 
     [delegate twitpicEngine:self didUploadImageWithResponse:nil]; // Nil should mean "upload failed" to the delegate 
    } 
    [pool drain]; 
    [urlRequest release]; 
} 

私たちは、あなたの質問に答えるに役立つだろう一つのこと:あなたが応答コードが0であると述べているが、(あなたがresponseStringで録音)応答の残りの部分が何であるかを述べていません。ステータスコードが[200,300]の範囲内にあれば印刷するだけなので、問題の原因は見えないかもしれませんが、Twitpic が戻ってくるかもしれません。チェックアウトする価値があります(上記の私のコードでこれを行いました)。

+0

このURLのhttps://twitpic.com/api/uploadAndPost私はレスポンスコードを0、レスポンスデータをnullにしています。私はそれをどうしたらいいですか? –

+0

私はまだ手がかりがありません - Twitpic APIはあなたのようなエラーケースを文書化する必要があります。応答のステータスコードは何ですか?あなたのPOST本体をAPIが予期しているものに対してどの程度徹底的にチェックしましたか? –

関連する問題