c#HTTPWebRequest POST到Objective-c NSMutableURLRequest statusCode 405

时间:2013-08-27 21:02:36

标签: objective-c post nsmutableurlrequest

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的任何帮助或指示都会有很大帮助。

1 个答案:

答案 0 :(得分:1)

这些要求并不完全相同。 C#示例使用查询参数/DebugUser?userName=<username>&password=<password>发送POST请求,obj-c使用form-urlencoded data /userName=<username>&password=<password>发送POST请求。我想这个问题是URI路径中的这个小错误(大多数那些小的,愚蠢的错误需要更多的时间来解决而不是真正的问题..;))。此外,我建议url编码params,在此示例中,您的用户名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");
    }
}