如何通过URL将数据发送到服务器。[iOS]

时间:2014-06-06 05:52:09

标签: ios json

如何使用POST方法通过URL将数据发送到服务器。

我的数据如下:

  json == {
Signup =     {
    email = test;
    password = 123;
    username = test;
 };
}

我的网址是这样的:

http://192.168.1.122/~test/sample/index.php/Api/signup

请建议我。我在最近2天坚持这个。请帮帮我。

数据格式为JSON。

2 个答案:

答案 0 :(得分:1)

您可以执行类似的操作,使用JSON数据发送简单的帖子请求

  -(void)sendPostData{

 NSString *urlStr = @"http://me.com";
 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
 NSURL *url = [NSURL URLWithString:urlStr];

NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:user.userName,@"username",user.password,@"password",user.email,@"email", nil];
    NSError *error;

   NSData* bodyData = [NSJSONSerialization dataWithJSONObject:info
                                                       options:kNilOptions error:&error];


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:data];
    [request setValue:[NSString stringWithFormat:@"%d", [data length]] forHTTPHeaderField:@"Content-Length"];


    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *responseFromRequest, NSData *data, NSError *error)
     {
         NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)responseFromRequest;
         NSInteger code = [httpResponse statusCode];

         }];
}

答案 1 :(得分:0)

看看我的GitHub回购JWURLConnection enter link description here,这对你有所帮助。

如果您定位API,我也会推荐JWRESTClient