【问题标题】:JSON POST Request on the iPhone (Using HTTPS)iPhone 上的 JSON POST 请求(使用 HTTPS)
【发布时间】:2011-05-04 09:54:56
【问题描述】:

我有一个托管的 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(模拟器)拨打电话时发生的事情,这就是它给我的信息:

我注意到的唯一奇怪的事情是它说“未为此主机启用 SSL 代理:在代理设置中启用 SSL 位置”。有谁知道这意味着什么?(这也发生在我工作的 Windows 客户端中)。

我刚刚在我的 Windows 客户端上运行了这个,唯一不同的是请求和响应文本是加密的。为了使用安全的 HTTP 连接来执行此操作,我是否遗漏了什么?

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

我也在使用这些方法:

- (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”的服务器,这可能会使您的机密信息面临风险。

【问题讨论】:

  • 如果您的服务器中的日志有什么有趣的内容,您能看到它们吗?
  • 我现在无法访问它们。我知道该服务已设置并与其他客户合作。

标签: iphone objective-c json ssl https


【解决方案1】:

dic 是带有对象和键的 NSMutable 字典。 baseUrl 是您的服务器网络服务 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"];

【讨论】:

    【解决方案2】:

    改变

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

    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
    

    【讨论】:

      【解决方案3】:

      已修复!

      改变:

      [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;
          }
      }
      

      【讨论】:

      • 顺便说一句,你没忘记“return NO”吗?在最后一个方法的最后一行?
      • 我不确定,我将 YES 返回到 void 方法。现在不记得为什么了。
      • @ing0 你能把这行翻译成 swift plz [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
      • @QadirHussain 抱歉,我写的不是很快。不过看看这个答案:stackoverflow.com/a/24321320/143979
      【解决方案4】:

      我根本不了解 Objective C,但尝试将 Accept 标头设置为 application/json 而不是 application/jsonrequest

      【讨论】:

      • 早些时候尝试过。无论如何都应该这样吗?刚刚又做了一次,我仍然得到同样的反应! :(
      • application/json 绝对是 JSON 数据的正确 MIME 类型。见stackoverflow.com/questions/477816/the-right-json-content-type
      • 您确定您的 Web 服务接受 url 编码格式的数据并以 json 格式响应吗?如果您执行 curl 命令并在 obj-C 中编写相同的程序,则很容易找出问题所在
      • 如果您发布了 WCF 服务的源代码和特别配置,也会很有帮助。另外,您是否尝试过访问错误消息中的服务帮助页面?
      • 不幸的是我没有编写服务。我有一个 .NET 应用程序使用类似的过程完全按照我的意愿进行操作。所以我知道这不是服务器问题!
      猜你喜欢
      • 2014-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多