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/"];
:
而在當前的方法,添加這些行內容類型:應用程序/ JSON你試過嗎? –
我沒有和它的工作,謝謝指出。 – kanstraktar