Searcher_安然 2014-07-12 01:44 采纳率: 0%
浏览 2707

IOS 向PHP服务器发送json数据 PHP服务器解析不到,格式有什么问题吗?

NSURL *url=[NSURL URLWithString:urlString];

NSMutableURLRequest *requests = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50];

[requests setHTTPMethod:@"POST"];

NSString *postParams = [NSString stringWithFormat:@"{\"token\":\"json\",\"account\":\"%@\",\"password\":\"%@\"}",username,password];
//NSDictionary *jsonDic=[NSDictionary dictionaryWithObjectsAndKeys:@"ios_json_data",@"token",@"testid",@"account",@"testid",@"password", nil];

//NSString *jsonStr=[NSString jsonStringWithDictionary:jsonDic];

NSData *data =[postParams dataUsingEncoding:NSUTF8StringEncoding];

[requests setValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];
[requests setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];


[requests setHTTPBody:data];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:requests success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    NSLog(@"Success  \n======url===%@ \n====request.httpBody====%@   \n===response===%@  \n===json===%@",requests.URL,[[NSString alloc] initWithData:requests.HTTPBody encoding:NSUTF8StringEncoding],response,JSON);

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    NSLog(@"falure============%@  %@  %@  %@",requests,response,error,JSON);
}];

[operation start];
  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-02 06:45
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在您的代码中,有几点需要注意:

    1. @"ios_json_data":这应该是一个字符串,而不是一个字典。您可能想要使用@"ios_json_data"作为键,将要转换为字典的值作为值。

    2. NSString *postParams = [NSString stringWithFormat:@"{\"token\":\"json\",\"account\":\"%@\",\"password\":\"%@\"}",username,password];:这里,@"%@" 是一个占位符,用于替换usernamepassword。您应该使用实际的用户名和密码字符串来替换它们。

    3. NSHTTPURLResponse *responseNSError *error:这些变量似乎不需要定义或初始化。您可以直接调用它们,并检查错误。

    4. @"application/json":这是告诉iOS应用程序这是一个JSON请求。如果您不希望将响应转换为JSON对象,可以更改为其他类型(例如HTML、XML)。

    根据上述修改后的代码,请尝试运行您的程序并查看输出结果。如果仍然出现问题,请提供更多的信息以便进一步帮助。

    评论

报告相同问题?