As the development of unmanned aerial vehicle (UAV) communication in the residential and commercial areas, different from the traditional wireless sensor networks (WSNs), in this paper we consider a two-layer wireless networks for data gathering, one is sensor nodes to UAVs layer, the other one is UAVs to the outside layer. The sensor nodes sense data and transmit to UAVs, and then UAVs send data to the outside. In this paper, we only focus on the first layer, and we suppose the capacity is sufficient for UAVs to transmit their gathered data in the second layer. The sensor nodes aim to maximize the total data transmitting rate. Because of the limited resources (i.e. limited bandwidth, limited energy of each node, and so on) in the system, thus how to allocate the limited resources to maximize the total data transmitting rate is challenging, and it is necessary to propose an efficient algorithm to allocate the resources. We formulate the problem that jointly considers bandwidth allocation and energy allocation to maximize the total transmitting rate while guarantees the rate in each time slot for each sensor node. Then an optimal algorithm based on dynamic programming named DPBA is proposed. Finally, we conduct the extensive simulation to compare our proposed algorithm and the benchmark algorithm (i.e. equal resource allocation algorithm, denoted by ERAA). Simulation results show that our proposed algorithm outperforms the benchmark algorithm.