JSON POST Request on the iPhone (Using HTTPS)

后端 未结 4 499
攒了一身酷
攒了一身酷 2020-12-23 15:47

I have a WCF service hosted and I\'m trying to use it within an iPhone app as a JSON POST request. I plan on using the JSON serializer later, but this is what I have for the

相关标签:
4条回答
  • 2020-12-23 15:58

    FIXED!

    Changed:

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

    to:

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

    You also need these two methods:

    - (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;
        }
    }
    
    0 讨论(0)
  • 2020-12-23 16:00

    change

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

    to

    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
    
    0 讨论(0)
  • 2020-12-23 16:04

    dic is NSMutable Dictionary with object and keys. baseUrl is your server 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"];
    
    0 讨论(0)
  • 2020-12-23 16:18

    I don't know Objective C at all, but try setting the Accept header to application/json instead of application/jsonrequest.

    0 讨论(0)
提交回复
热议问题