IOS 使用 POST、GET 提交 JSON 数据到服务器

最近被安排了一项在 IOS 下 POS T数据的任务,在 Google 的帮助下总算是作出来了。网上的教程不全、乱、缺乏一个全方位适合初级开发者的教程。ios

阅读本教程你须要:

  • 引用开源库 ASIHTTPRequest(负责网络通讯)、JSONKit(负责封装和解析JSON数据)
  • 管理开源库则须要工具 cocoapods(配置 ruby 和 gem),这是安装教程

好的,如今假设里上述工具都已经配置好了

  • 新建一个工程,我以 Demo 为例 /Users/Demo
  • 在命令终端中进入 Demo 目录
  • 用 vim 命令新建一个文件 Podfilegit

    输入命令 vim Podfilegithub

    按下 i 键,进入输入模式
    内容为:json

    platform :ios
        pod 'ASIHTTPRequest'

    按下 esc 进入命令模式,连按两次大写的 Z 保存并退出 vimvim

  • 输入命令 pod install 等待 出现xcode

    [!] From now on use Demo.xcworkspace.ruby

    在 finder 中打开 xcworkspace 来开启工程(进行此操做最好先把 Xcode 关闭,否则会看到“xxx 已经在xcode中打开的提示”)网络

  • 把 github 上的 JSONKit 搞下来app

    git clone https://github.com/johnezang/JSONKit.git
  • 导入头文件工具

    #import "JSONKit.h"
    #import <ASIHTTPRequest/ASIHTTPRequest.h>

在这里须要处理两个 bug

  • JSONKit 不支持 arc 模式,因此在 Build Phases 中把 JSONKit.m Compiler Flags 填入“-fno-objc-arc”
  • 不支持古老的 isa,因此你要这样作

    Include <objc/runtime.h>.

    Replace everything like array->isa =_JKArrayClass; with object_setClass(array, _JKArrayClass)

    And everything like class = array.isa with class = object_getClass(array)

好的,如今开始写代码了

假设咱们要上传的 JSON 格式是这样的:

{"email":"chenyu380@gmail.com","password":"FxxkYourAss"}

一个登陆方法

-(NSDictionary*)Login:(NSString *)email password:(NSString *)password
  {
  NSMutableDictionary *resultsDictionary;// 返回的 JSON 数据
  NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:password, @"password",email,@"email",nil];
  if ([NSJSONSerialization isValidJSONObject:userDictionary])
  {

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error];
    NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
    NSURL *url = [NSURL URLWithString:@"http://seanchense.com/login"];

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request addRequestHeader:@"Content-Type" value:@"application/json; charset=utf-8"];
    [request addRequestHeader:@"Accept" value:@"application/json"];

    [request setRequestMethod:@"POST"];
    [request setPostBody:tempJsonData];
    [request startSynchronous];
    NSError *error1 = [request error];
    if (!error1)
    {
        NSString *response = [request responseString];
        NSLog(@"Test:%@",response);
        NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding];

    }
  }

  return resultsDictionary;
  }

好的如今完成了

相关文章
相关标签/搜索