2012-09-28 41 views
1

我試圖做的通過HTTP後沒有更迭這裏是我的代碼HTTP POST目標C

NSError *error; 
NSHTTPURLResponse *response; 

NSData *posting = 
[NSJSONSerialization dataWithJSONObject:[input createJsonDictionary] 
           options:0 
            error:&error]; 
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", kURL]]; 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; 

[urlRequest setHTTPMethod:@"POST"]; 
[urlRequest setValue:@"application/json" 
    forHTTPHeaderField:@"Content-Type"]; 
[urlRequest setValue:[NSString stringWithFormat:@"AuthToken %@",token] 
    forHTTPHeaderField:@"Authorization"]; 
[urlRequest setHTTPBody:posting]; 

NSData *urlResponse = 
[NSData dataWithData:[NSURLConnection sendSynchronousRequest:urlRequest 
              returningResponse:&response error:&error]]; 
NSDictionary *jsonDictionary = 
[NSJSONSerialization JSONObjectWithData:urlResponse 
           options:0 
            error:&error]; 

NSLog(@"status code: %i", [response statusCode]); 

NSLog(@"URL: %@", [urlRequest URL]); 
NSLog(@"header: %@ \n method: %@", [urlRequest allHTTPHeaderFields], [urlRequest HTTPMethod]); 
NSLog(@"body: %@\n", [[NSString alloc] initWithData:[urlRequest HTTPBody] encoding:NSUTF8StringEncoding]); 

在NSLog的我找回狀態碼500,有一個錯誤。但是當我嘗試使用捲曲來執行相同的命令時

curl --request POST -H "Content-Type: application/json" 
-H "Authorization: AuthToken TOKEN" --data '{"DATA"}' -sL 
-w "\\n%{http_code} %{url_effective}\\n" https://URL.com 

我找回狀態碼201,成功。我的代碼中似乎沒有東西。同樣在urlRequest的NSLogs中,它們等於curl命令中的whats。有什麼我做錯了嗎?

+0

有人可能會想出這個答案,但我可以建議使用[wireshark](http://www.wireshark.org/)捕獲和分析這兩個請求(從curl和你的應用程序),並看看對於它們之間的差異,你可以使用這種方法解決你的問題。 – carlossless

回答

0

找到我自己的答案。問題是我的代碼正在同步調用服務器,並且服務器沒有設置爲執行同步Web調用。相反,我不得不使用NSURLConnection的即時變量,並異步執行「sendAsynchronousRequest:queue:completionHandler:」的調用,並使用instant變量的方法start/cancel。

0

而不是

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", kURL]]; 

嘗試

NSString *urlText = [NSString stringWithFormat:@"%@", kURL]; 
urlText = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
NSURL *url = [NSURL URLWithString:urlText]; 
+0

仍然得到狀態碼500 –

+0

抱歉幫不上忙。我通常在ASIHTTPRequest上使用我自己的封裝來處理幾天前公佈的網絡通信。 – tGilani