您可能要檢查jsonData
您接收響應,並確保它的實際JSON。所以,正如Ashutosh所建議的那樣,您應該從sendSynchronousRequest
檢查NSError
。此外,如果JSON解析失敗,請檢查NSData
對象:
NSError *requestError;
NSURLResponse *response;
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
// examine the HTTP status code (if any)
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
int statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode != 200) {
NSLog(@"%s: sendSynchronousRequest responded with statusCode = %d; expected 200", __PRETTY_FUNCTION__, statusCode);
}
}
// examine the `requestError` (if any)
if (!jsonData) {
NSLog(@"%s: sendSynchronousRequest error = %@", __PRETTY_FUNCTION__, requestError);
}
// now try to parse the response, reporting the JSON object if successful; reporting the `NSString` representation of the `jsonData` if not
NSError *parseError;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&parseError];
if (results) {
NSLog(@"%s: JSON parse succeeded; results = %@", __PRETTY_FUNCTION__, results);
} else {
NSLog(@"%s: JSON parse failed; parseError = %@"; jsonData = %@", __PRETTY_FUNCTION__, parseError, [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
}
有了類似的東西,你就可以準確地診斷是怎麼回事。由於VaaChar觀察到(+1),您原始問題的JSON請求無效(儘管您後來修復了該問題)。上面的代碼可以幫助你識別錯誤,就像你已經看到了服務器的迴應。
您可以使用NSJSONSerialization
爲您構建它,以確保您擁有有效的JSON,而不是手動構建您的JSON,而不是使用這種簡單的錯誤。因此:
NSDictionary *params = @{@"devID" : @"I:73899EAB-BB4F-4AE5-A691-8505E6AF0C3A",
@"msisdn" : @"+380503424248"};
NSError *jsonError;
NSData *body = [NSJSONSerialization dataWithJSONObject:params options:0 error:&jsonError];
if (!body) {
NSLog(@"%s: dataWithJSONObject failed: %@", __PRETTY_FUNCTION__, jsonError);
} else {
request.HTTPBody = body;
}
來源
2014-05-15 13:48:56
Rob
你在請求的響應收到此錯誤? – Ashutosh
順便說一句,如果你發送JSON請求,約定會建議你的請求指定它正在這樣做,例如, '[request setValue:@「application/json」forHTTPHeaderField:@「Content-type」];'。有時編寫Web服務代碼是爲了驗證請求的內容類型是否符合預期。 – Rob
是的!這是我的代碼中的很多錯誤,但有助於你的幫助,我已經糾正它,並得到正確的要求。 –