2013-08-27 27 views
1

什麼是好的,在C#中簡單的談到了將在目標C熊C#HttpWebRequest的POST到Objective-C NSMutableURLRequest的StatusCode 405

 static private void AddUser(string Username, string Password) 
    { 
     HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://192.168.1.10:8080/DebugUser?userName=" + Username + "&password=" + Password)); 

     request.Method = "POST"; 
     request.ContentLength = 0; 

     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

     Console.Write(response.StatusCode); 
     Console.ReadLine(); 
    } 

工作正常,但是當我試圖將其轉換爲Objective- C(IOS),我得到的只是「連接狀態405方法不允許」

-(void)try10{ 
    NSLog(@"Web request started"); 
    NSString *user = @"[email protected]"; 
    NSString *pwd = @"myEazyPassword"; 
    NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",user,pwd]; 
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding]; 
    NSString *postLength = [NSString stringWithFormat:@"%ld", (unsigned long)[postData length]]; 
    NSLog(@"Post Data: %@", post); 

    NSMutableURLRequest *request = [NSMutableURLRequest new]; 
    [request setURL:[NSURL URLWithString:@"http://192.168.1.10:8080"]]; 
    [request setHTTPMethod:@"POST"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:postData]; 

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if(theConnection){ 
     webData = [NSMutableData data]; 
     NSLog(@"connection initiated"); 
    } 
} 

任何幫助或指示在IOS上使用POST將是一個很大的幫助。

+0

用戶名,用戶名中objC。在objC中使用小寫n可以嗎? –

+0

另外,你的objC代碼不包含對DebugUser的引用,你發佈到/ –

回答

1

這些請求並不完全相同。 C#示例向查詢參數?userName=<username>&password=<password>發送POST請求至/DebugUser,obj-c通過表單urlencoded數據userName=<username>&password=<password>發送POST請求至/。我想這個問題是URI路徑中的這個小錯誤(大多數那些小的,愚蠢的錯誤需要更多的時間來解決,而不是真正的問題..))。此外,我會建議網址編碼參數,在這個例子中,您的用戶名[email protected]應編碼爲me%40inc.com爲有效的url/form-url編碼數據。另見我關於伊娃的代碼註釋。

類似的東西應該工作(書面上的蒼蠅,我沒有編譯發佈前/檢查):在C#

-(void)try10{ 
    NSString *user = @"me%40inc.com"; 
    NSString *pwd = @"myEazyPassword"; 
    NSString *myURLString = [NSString stringWithFormat:@"http://192.168.1.10:8080/DebugUser?username=%@&password=%@",user,pwd]; 
    NSMutableURLRequest *request = [NSMutableURLRequest new]; 
    [request setURL:[NSURL URLWithString:myURLString]]; 
    [request setHTTPMethod:@"POST"]; 

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

    if(theConnection){ 
     // I suppose this one is ivar, its safer to use @property 
     // unless you want to implement some custom setters/getters 
     //webData = [NSMutableData data]; 
     self.webData = [NSMutableData data]; 
     NSLog(@"connection initiated"); 
    } 
} 
+0

哇我至少嘗試了10種不同的方法,並且整天都有同樣的小錯誤!我嘗試過的一些方法非常龐大。這很好,很簡單,很有效。 –