0

このコードを使用して JSON を .NET サービスに送信し、ユーザーを登録しています。

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                deviceID, @"DeviceId",
                                model, @"DeviceModel",
                                user, @"Username",
                                pass, @"Password",
                                email, @"email",
                                nil];

    NSDictionary *consumer = [NSDictionary dictionaryWithObject:dictionary forKey:@"consumer"];
    NSLog(@"%@", consumer);

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:consumer
                                                       options:kNilOptions
                                                         error:&error];
    NSLog(@"%@", error);

    NSString *urlString = @"http://aservice.co.uk/services/service.svc/RegisterConsumer";

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:jsonData];
    NSURLResponse *response = NULL;
    NSError *requestError = NULL;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
    NSLog(@"%@", responseString);
    NSLog(@"%@", requestError);

のJSON結果を受け取るので、これは正常に機能します{"RegisterConsumerResult":"True"}

既に存在することがわかっているユーザー名を登録しようとすると、次の HTML が responseString として返されます。

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">   <head>
    <title>Request Error</title>
    <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>   </head>   <body>
    <div id="content">
      <p class="heading1">Request Error</p>
      <p>The server encountered an error processing the request. See server logs for more details.</p>
    </div>   </body> </html>

明らかに、これは実際のエラーを返すのではなく、エラーがあったことを示す Web ページを返すだけです。サービスから実際のエラー コードを取得する方法がありませんか? サービスが何らかの形でエラーを応答として送信している可能性はありますか?

編集--言及するのを忘れていましたが、実際のerrorResponseはnilです.HTMLが返されたため、実際のリクエストは成功したと分類されていると思います。

4

1 に答える 1

1

まず、400 以上のエラーを次のように処理できるように、ステータス コードを確認します。

NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSUInteger statusCode = [(NSHTTPURLResponse*)response statusCode];
//Then do your error checking. 

AFNetworking を使用したい場合、これを行うのは非常に簡単です。ライブラリを追加するだけです (ここにあります: http://afnetworking.com )。次に、次のようにします。

//NOTHING CHANGED TIL NEXT COMMENT
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                            deviceID, @"DeviceId",
                            model, @"DeviceModel",
                            user, @"Username",
                            pass, @"Password",
                            email, @"email",
                            nil];

NSDictionary *consumer = [NSDictionary dictionaryWithObject:dictionary forKey:@"consumer"];
NSLog(@"%@", consumer);

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:consumer
                                                   options:kNilOptions
                                                     error:&error];
NSLog(@"%@", error);
//Start to use AFNetworking

    NSURL *baseUrl = [NSURL URLWithString:@"http://aservice.co.uk/services/service.svc/"];
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseUrl];

NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:@"RegisterConsumer" parameters:dictionary];
[request setHTTPBody:jsonData];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"SUCESS");
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"FAILED WITH STATUS CODE %d - error description: %@", response.statusCode, error);
}];

[operation start];

これは非同期接続を使用しており (そうするべきです!)、成功ブロックで次のステップを呼び出すことができます。

私はこれをテストしませんでしたが、あなたがする必要があることに対してうまくいくはずです(または非常に近い)。

更新 おそらく、このコード(私はHEREから取得しました)を使用して、ヘッダーで提供されているデータの種類を確認し、それが役立つかどうかを確認できます。

if ([response respondsToSelector:@selector(allHeaderFields)]) {
    NSDictionary *dictionary = [response allHeaderFields];
    NSLog([dictionary description]);
}
于 2012-11-29T15:59:05.503 に答える