代码之家  ›  专栏  ›  技术社区  ›  ingh.am

iPhone上的json post请求(使用https)

  •  11
  • ingh.am  · 技术社区  · 14 年前

    我托管了一个WCF服务,我正试图在iPhone应用程序中使用它作为JSON Post请求。我计划稍后使用JSON序列化程序,但这就是我对请求的理解:

        NSString *jsonRequest = @"{\"username\":\"user\",\"password\":\"letmein\"}";
        NSLog(@"Request: %@", jsonRequest);
    
        NSURL *url = [NSURL URLWithString:@"https://mydomain.com/Method/"];
    
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody: requestData];
    
        [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
    

    在收到的数据中,我只是将其打印到控制台:

    - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        NSMutableData *d = [[NSMutableData data] retain];
        [d appendData:data];
    
        NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
    
        NSLog(@"Data: %@", a);
    }
    

    在这个回复中,我得到了这样的信息:

    Data: <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Request Error</title>
        <style>
            <!-- I've took this out as there's lots of it and it's not relevant! -->
        </style>
      </head>
      <body>
        <div id="content">
          <p class="heading1">Request Error</p>
          <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="https://mydomain.com/Method/help">service help page</a> for constructing valid requests to the service.</p>
        </div>
      </body>
    </html>
    

    有人知道为什么会发生这种事吗?我哪里出错了?

    我读过关于使用 ASIHTTPPost 但是我不能让演示在iOS4中运行:(

    谢谢

    编辑:

    我只是习惯了 CharlesProxy 当我从iphone(模拟器)打电话时,为了嗅出发生了什么,这就是它给我的: alt text

    唯一奇怪的是,我注意到它说“没有为这个主机启用SSL代理:在代理设置、SSL位置中启用”。有人知道这是什么意思吗? (这也发生在我工作的Windows客户机中)。

    我刚刚在我的Windows客户机上运行了这个程序,唯一不同的是请求和响应文本是加密的。为了使用安全的HTTP连接,我是否缺少某些内容?

    新编辑: 这适用于非HTTPS请求,例如: http://maps.googleapis.com/maps/api/geocode/json?address=UK&sensor=true . 所以我想问题是让iPhone通过SSL正确地发送帖子?

    我也在使用这些方法:

    - (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
    {
        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
            forAuthenticationChallenge:challenge];
        }
    
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
    
    - (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
    {
        if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
        {
            return YES;
        }
    }
    

    这让我走得这么远。如果我不使用它们,我会收到一个错误消息,说:

    此服务器的证书无效。您可能正在连接一个假装为mydomain.com的服务器,这可能会使您的机密信息处于危险之中。

    4 回复  |  直到 10 年前
        1
  •  12
  •   ingh.am    14 年前

    固定的!

    改变:

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    

    到:

    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    

    您还需要以下两种方法:

    - (void) connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
    {
        if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
            forAuthenticationChallenge:challenge];
        }
    
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
    
    - (void) connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
    {
        if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
        {
            return YES;
        }
    }
    
        2
  •  3
  •   Jon    14 年前

    我根本不知道目标C,但是尝试将接受头设置为 application/json 而不是 application/jsonrequest

        3
  •  0
  •   Maulik Vekariya    11 年前

    改变

    NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    

    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
    
        4
  •  0
  •   Vibhooti    10 年前

    dic是具有对象和键的不可变字典。 baseurl是您的服务器WebService URL。

     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                           options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
       NSString *encodedString = [jsonString base64EncodedString];
    
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@wsName",baseUrl]];
        NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
        [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setValue:encodedString forHTTPHeaderField:@"Data"];