iOS:发送基本的http post请求并解析JSON响应

时间:2014-07-12 21:55:36

标签: ios json http-post

我从ios android开始,我正在尝试找出如何发送注册页面的基本http发布请求,然后获取http响应和读取错误使用php中的json_encode函数返回。例如:

if(minMaxRange(5,25,$username))
    {
        $errors[] = lang("ACCOUNT_USER_CHAR_LIMIT",array(5,25));
        $data = array('userCharLimit' => 'Your username must be between 5 and 25 characters in length');
        print (json_encode($data)); 
    }

我一直在搜索stackoverflowgoogle,我只能在发送JSON和返回JSON时找到合适的文档。我对如何发送http post请求有一个想法,但我对从响应中检索值无能为力。

这是我在JSON发送帖子后检索Android值的方法:

// Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            String jsonResult = inputStreamToString(
                    response.getEntity().getContent()).toString();
            JSONObject object = new JSONObject(jsonResult);
            if (object.has("userCharLimit")) {
                String userCharLimit = object.getString("userCharLimit");
                error = error + userCharLimit;
            }
private StringBuilder inputStreamToString(InputStream is) {
    String rLine = "";
    StringBuilder answer = new StringBuilder();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

    try {
        while ((rLine = rd.readLine()) != null) {
            answer.append(rLine);
        }
    }

    catch (IOException e) {
        e.printStackTrace();
    }
    return answer;

ios会相对相似吗?

1 个答案:

答案 0 :(得分:2)

Here是从JSON检索所有值并获取特定值的良好链接。

要检索POST数据,您需要稍微编辑代码。

' connectionDidFinishLoading'方法是您将看到如何获取值的方法。

这真的帮助了我。只是传递这个发现。

祝你好运!

编辑**随着链接不断下降。以下代码的作者是" JR"来自https://agilewarrior.wordpress.com

@interface spike1ViewController()
@property (nonatomic, strong) NSMutableData *responseData;
@end

@implementation spike1ViewController

@synthesize responseData = _responseData;

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSLog(@"viewdidload");
    self.responseData = [NSMutableData data]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyAbgGH36jnyow0MbJNP4g6INkMXqgKFfHk"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"didReceiveResponse");
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {        
    [self.responseData appendData:data]; 
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {    
    NSLog(@"didFailWithError");
    NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    // show all values
    for(id key in res) {

        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;

        NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

    // extract specific value...
    NSArray *results = [res objectForKey:@"results"];

    for (NSDictionary *result in results) {
        NSString *icon = [result objectForKey:@"icon"];
        NSLog(@"icon: %@", icon);
    }

}

- (void)viewDidUnload {
    [super viewDidUnload];
}

@end

UPDATE **

为避免在面向iOS 9及更高版本的应用中收到弃用警告,您可以使用NSURLSession及其块样式格式。这是一个想法:

_request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"YOUR URL TO POST DATA TO"]];
[_request setHTTPMethod:@"POST"];
[_request addValue:post forHTTPHeaderField:@"METHOD"];
NSData *data = [post dataUsingEncoding:NSUTF8StringEncoding];
[_request setHTTPBody:data];
[_request addValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *serviceConnection = [session dataTaskWithRequest:_request
                                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                                 {

                                                     if (!error) {

                                                         //BEGIN PARSING RESPONSE.

                                                     }else{

                                                         //AN ERROR OCCURED. HANDLE APPROPRIATELY.
                                                     }

                                                 }];
        [serviceConnection resume];