2014-06-17 14 views
0

I'trying擺脫http://schematic-ipsum.herokuapp.com/一些隨機JSON,但我得到的響應碼400發送JSON原理圖存有

這裏是代碼我使用

+ (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString 
{ 
    NSArray *dataToReturn; 

    // if urlString is nil, we default it to our server 
    if(!urlString) urlString = JSON_SERVER; 

    // of course we need to turn the string into a valid array 
    NSURL *url = [NSURL URLWithString:urlString]; 

    /* 
     prepare the post 
    */ 

    // we need to catch possible errors 
    NSError *error; 

    // turn our arguments into NSData 
    NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error]; 

    // we need the post' length 
    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]]; 

    // create the url request 
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:url]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
    [request setValue:@"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 

    // here we'll check the server response 
    NSHTTPURLResponse *response = nil; 

    // here's our data from the server 
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

    if ([response statusCode] >=200 && [response statusCode] <300) 
    { 
     // all good, let's see what we've got 
     NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; 
     NSLog(@"Response ==> %@", responseData); 

     // parse the response into a friendly format 
     dataToReturn = [[NSArray alloc] initWithArray:[self returnJSONFromData:urlData]]; 
    } else { 
     // somethin went wrong 
     NSLog(@"Response code: %ld", (long)[response statusCode]); 
     // check if it's our fault 
     if (error) { 
      NSLog(@"Server error: %@", [error localizedDescription]); 
     } 
    } 

    // return our formatted array or nil 
    return dataToReturn; 
} 

+ (NSArray *)returnJSONFromData:(NSData *)urlData 
{ 
    NSArray *dataToReturn; 

    NSError *e = nil; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &e]; 

    if (!jsonArray) { 
     NSLog(@"Error parsing JSON: %@", [e localizedDescription]); 
     dataToReturn = @[e]; 
    } else { 
     dataToReturn = [[NSArray alloc] initWithArray:jsonArray]; 
     NSLog(@"data from json: %@", dataToReturn); 
    } 

    return dataToReturn; 
} 

和我m這樣稱呼它,使用他們網站上的演示JSON:

NSDictionary *post = @{ @"type": @"object", @"properties": @{ @"id": @{ @"type": @"string", @"ipsum": @"id" }, @"name": @{ @"type": @"string", @"ipsum": @"name" }, @"email": @{ @"type": @"string", @"format": @"email" } }}; 
[RetrieveDataFromServer postData:post toServer:@"http://schematic-ipsum.herokuapp.com/"]; 
+1

- (NSString *)formatFormData:(NSDictionary *)dictionary { NSMutableArray *arrayPrefix = [NSMutableArray array]; NSMutableArray *arrayResult = [NSMutableArray array]; [self structureString:dictionary arrayPrefix:arrayPrefix arrayResult:arrayResult]; return [arrayResult componentsJoinedByString:@"&"];; } - (void)structureString:(NSDictionary *)dictionay arrayPrefix:(NSMutableArray *)arrayPrefix arrayResult:(NSMutableArray *)arrayResult { for(NSString *key in dictionay.allKeys) { NSObject *obj = [dictionay objectForKey:key]; if([obj isKindOfClass:[NSDictionary class]]) { [arrayPrefix addObject:key]; [self structureString:(NSDictionary *)obj arrayPrefix:arrayPrefix arrayResult:arrayResult]; } else { NSMutableString *string = [[NSMutableString alloc] initWithString:@""]; for(int i = 0; i < arrayPrefix.count; i++) { NSString *eachPrefix = arrayPrefix[i]; if(i == 0) { [string appendString:eachPrefix]; } else { [string appendString:[NSString stringWithFormat:@"[%@]", eachPrefix]]; } } if(arrayResult.count == 0) { [string appendString:[NSString stringWithFormat:@"%@=%@", key, obj]]; } else { [string appendString:[NSString stringWithFormat:@"[%@]=%@", key, obj]]; } [arrayResult addObject:string]; } } } 

而在當前的方法,添加這些行內容類型:應用程序/ JSON你試過嗎? –

+0

我沒有和它的工作,謝謝指出。 – kanstraktar

回答

1

您需要尊重服務器所採用的「表單數據」的語法。要獲得此,您可以使用谷歌瀏覽器「檢查元素」,選擇「網絡」選項卡,然後做一個請求,你會看到這一點:

enter image description here

看「表單數據」部分,你會找出你的問題,這是因爲你沒有將正確的結構傳遞給服務器,以致服務器不理解。 enter image description here

enter image description here

我把服務器的默認參數是:

{ 
    "type": "object", 
    "properties": { 
    "id": { 
     "type": "string", 
     "ipsum": "id" 
    }, 
    "name": { 
     "type": "string", 
     "ipsum": "name" 
    }, 
    "email": { 
     "type": "string", 
     "format": "email" 
    }, 
    "bio": { 
     "type": "string", 
     "ipsum": "sentence" 
    }, 
    "age": { 
     "type": "integer" 
    }, 
    "avatar": { 
     "type": "string", 
     "ipsum": "small image" 
    } 
    } 
} 

因此數據必須像下面這樣的結構:

type:object 
properties[id][type]:string 
properties[id][ipsum]:id 
properties[name][type]:string 
properties[name][ipsum]:name 
properties[email][type]:string 
properties[email][format]:email 
properties[bio][type]:string 
properties[bio][ipsum]:sentence 
properties[age][type]:integer 
properties[avatar][type]:string 
properties[avatar][ipsum]:small image 

而且不要忘了在將其發送到服務器之前用百分比進行編碼,否則將再次失敗。 我試圖實現一個方法,它將您的字典和返回格式化的表單數據,它適用於這種情況,但我不確定在更一般的上下文。我會在這裏把它作爲參考發佈給你,這真是一團糟,對不起,但我沒有足夠的時間進行評論。根據他們的網頁

- (NSArray *)postData:(NSDictionary *)arguments toServer:(NSString *)urlString 
{ 
    // omitted 

    // turn our arguments into NSData 
    NSData *postData = [NSJSONSerialization dataWithJSONObject:arguments options:0 error:&error]; 
    NSString *stringTemp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding]; 
    stringTemp = [self formatFormData:arguments]; 
    // encode form date before sending to server 
    stringTemp = [stringTemp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    postData = [stringTemp dataUsingEncoding:NSUTF8StringEncoding]; 

    // omitted 
} 
+0

感謝您解決編寫此問題的所有麻煩。我必須首先嚐試馬修克拉克的解決方案,因爲它更容易實施並且工作。 – kanstraktar