2.通过iOS客户端访问我们搭建的api

一、简单的post请求
1.先确保你已经搭好了restful服务,不懂的请看链接:http://blog.csdn.net/lsdjfkjsdljfks/article/details/50722114

2.在之前创建好的UserResource.java类中添加以下方法

    @POST
    @Path("/saveUser")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public User saveUser(User user)
    {   
        return user;
    }

3.创建ios客户端

- (void)postWithJson
{
    //将数据包装好
    NSMutableDictionary *bookDict = [NSMutableDictionary dictionary];
    bookDict[@"bookName"] = @"math";
    bookDict[@"bookNumber"] = @"23424";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"id"] = @"44";
    dict[@"userName"] = @"sdfsd";
    dict[@"book"] = bookDict;
    //注意:如果是运行在真机上,请将localhost改为自己本机的ip地址
    NSString *urlStr = @"http://localhost/api/user/saveUser";
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    [request setHTTPMethod:@"POST"];

    //超时时间
    [request setTimeoutInterval:30];

    //设置请求内容格式
    [request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];

    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];

    [request setHTTPBody:bodyData];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"%@",error);
        } else {
            NSLog(@"%ld",[data length]);
            NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",aString);
            NSError *error = nil;
            NSDictionary *temp = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
            NSLog(@"session request \n %@",temp);

            if (error) {
                NSLog(@"%@",error);
            }
        }
    }];

    [task resume];
}

你可能感兴趣的:(ios,ios,java-EE)