ios - json 请求响应出现问题,得到空白响应

标签 ios web-services request browser response

我在 iOS 中的简单请求响应中遇到了一个问题,我在请求带有一个 post 参数的 url 时收到空白响应,其中该 url 在 Android 和网络浏览器中完美运行

详细的 friend ,我要打电话

http://example.com/GetCountries

具有以下 http post 参数

"key"="Abcd1234"

它以前可以工作,但从最近几天开始它不工作,如果我检查 NSError 它会向我显示网络连接丢失。

这里值得注意的另一件事是相同的服务器代码位于不同的 url 上并且工作正常,您可以按如下方式测试该 url

http://example.com/GetCountries

具有以下 http post 参数

"key"="Abcd1234"

这里是用于测试 ios 源代码的 dropbox 链接,该文件夹还包含 Web 服务 test.htm 文件,用于测试具有相同 post 参数的相同 url 在浏览器中工作但不在 ios 设备中工作。

测试代码: https://dl.dropboxusercontent.com/s/lqrl5b95j2s54mm/Testing.zip?token_hash=AAFgoNfUpQ4FkeswnPdGiMVzdMtSM6js9KySJm_OH6lZXQ&dl=1

谢谢

最佳答案

所以我无法让表单本身工作,但能够重新设计它以使其工作。请注意以下几点:

  • 您应该转换为 ARC!
  • 您需要对连接的强引用,以便稍后可以释放它(而不是在委托(delegate)方法中!)
  • 您需要委托(delegate)connectionSucceeded方法(记录响应!)

代码:

- (void)asynchronousRequest
{
    [activity startAnimating];

    NSString *requesturl = lblURL.text;
    NSLog(@"requesturl=%@", requesturl);
    NSURL *theURL = [NSURL URLWithString:requesturl];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"content-type"];
    [request setURL:theURL];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setTimeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];

    NSString *str = [NSString stringWithFormat:@"key=%@", [self URLencodedString:@"Abcd1234"]];
    NSLog(@"BODY: %@", str);
    NSData *body = [str dataUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"URL : %@", requesturl);
    NSLog(@"REQ : %@", request);

    [request setHTTPBody:body];
    [request addValue:[NSString stringWithFormat:@"%u", [body length]] forHTTPHeaderField:@"Content-Length"];


    NSLog(@"AllFields : %@", [request allHTTPHeaderFields]);
    NSLog(@"HTTPBody : %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
    NSLog(@"HTTPMethod : %@", [request HTTPMethod]);

    self.activeDownload = [NSMutableData data];

    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    assert(conn);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    assert([response isKindOfClass:[NSHTTPURLResponse class]]);
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    NSLog(@"GOT %d", [httpResponse statusCode]);

}
- (NSString *)URLencodedString:(NSString *)s
{
    CFStringRef str = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)s,  NULL,  (CFStringRef)@"!*'();:@&;=+$,/?%#[]",  kCFStringEncodingUTF8);
    NSString *newString = [(NSString *)str stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    if(str) CFRelease(str);
    return newString;
}

编辑:修改后的代码仍然不起作用:

- (void)asynchronousRequest
{

    [activity startAnimating];

    NSString *boundary = @"1010101010"; // DFH no need for the leading '--'
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];


    NSMutableDictionary *postVariables = [[NSMutableDictionary alloc] init];

    [postVariables setValue:@"Abcd1234" forKey:@"key"];


    NSString *requesturl = lblURL.text;

    NSMutableString *myStr = [[NSMutableString alloc] init];

    NSString *str;

    // DFH - strategy is to have each line append its own terminating newline/return
    str = [NSString stringWithFormat:@"--%@\r\n",boundary]; // DFH initial boundary
    [myStr appendString:str];


    NSArray *formKeys = [postVariables allKeys];
    for (int i = 0; i < [formKeys count]; i++) {
        str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n%@\r\n",[formKeys objectAtIndex:i],[postVariables valueForKey:[formKeys objectAtIndex:i]]];
        [myStr appendString:str];

        str = [NSString stringWithFormat:@"--%@\r\n",boundary]; // DFH mid or terminating boundary
        [myStr appendString:str];
    }
    NSLog(@"BODY: %@", myStr);
    NSData *body = [myStr dataUsingEncoding:NSUTF8StringEncoding];

    requesturl = [self encodeStringForURL:requesturl];
    NSLog(@"requesturl=%@", requesturl);

    NSURL *theURL = [NSURL URLWithString:requesturl];

    self.activeDownload = [NSMutableData data];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:theURL];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
    [request setTimeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // DFH you add addValue, I always use setValue

    NSLog(@"URL : %@", requesturl);
    NSLog(@"REQ : %@", request);
    NSLog(@"ContentType \"%@\"", contentType);

    if(body)
    {
        [request setHTTPBody:body];
    }
    NSLog(@"AllFields : %@", [request allHTTPHeaderFields]);
    NSLog(@"HTTPBody : %@", [[NSString alloc] initWithData:[request HTTPBody] encoding:NSUTF8StringEncoding]);
    NSLog(@"HTTPMethod : %@", [request HTTPMethod]);

    conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    assert(conn);
}

关于ios - json 请求响应出现问题,得到空白响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607607/

相关文章:

iphone - Xcode5 - 无法添加我的 Apple ID

ios - 在 swift 中为 View 创建 IBOutlet 时,基类附加了一个?

ruby-on-rails - 获取哈希符号后的请求部分

c# - WCF 在大约 10 次左右的调用后停止响应( throttle )

java - 如何正确配置网络应用程序,以便 axis2 找到所需的模块?

python - 从网站抓取分页链接的网页抓取问题

node.js - 使用特定网络接口(interface)执行请求

ios - 修复音频播放器错误

python - 如何为现有项目自动创建新的 xcode 目标

java - 验证 SOAP 响应 xml 时间戳和签名 X509 spring-ws-security