1

C# 中美好而简单的东西在 Objective C 中变成了熊

        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 = @"me@inc.com";
    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 的帮助或指示都会有很大帮助。

4

1 回答 1

1

这些要求并不完全相同。C# 示例/DebugUser使用查询参数发送 POST 请求?userName=<username>&password=<password>,obj-c/使用 form-urlencoded 数据发送 POST 请求userName=<username>&password=<password>。我想这个问题是 URI 路径中的这个小错误(大多数是那些小的、愚蠢的错误比真正的问题需要更多的时间来解决......;))。此外,我建议对参数进行 url 编码,在此示例中,您的用户名me@inc.com应编码为me%40inc.com有效的 url/form-url 编码数据。另请参阅我关于 ivar 的代码评论。

类似的东西应该可以工作(即时编写,我没有在发布前编译/检查):

-(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");
    }
}
于 2013-08-27T23:25:03.553 回答