【问题标题】:iOS: Send basic http post request and parse JSON responseiOS:发送基本的 http post 请求并解析 JSON 响应
【发布时间】:2014-07-12 21:55:36
【问题描述】:

我从ios 开始,从android 开始,我试图弄清楚如何为注册页面发送基本的http post 请求,然后获取http 响应并读取使用@ 返回的错误987654323@ php 中的函数。示例:

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 请求有一个想法,但我对从响应中检索值一无所知。

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

// 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会比较相似吗?

【问题讨论】:

    标签: ios json http-post


    【解决方案1】:

    Here 是一个很好的链接,用于从 JSON 中检索所有值并获取特定值。

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

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

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

    祝你好运!

    编辑** 以防链接断开。下面代码的作者是来自https://agilewarrior.wordpress.com的“JR”

    @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
    

    更新**

    为避免在面向 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];
    

    【讨论】:

      猜你喜欢
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 2016-05-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      相关资源
      最近更新 更多