An optimal method for resource allocation based on contract theory is proposed to improve energy utilization. In heterogeneous networks (HetNets), distributed heterogeneous network architectures are designed to balance different computing capacities, and MEC server gains are designed based on the amount of allocated computing tasks. An optimal function based on contract theory is developed to optimize the revenue gain of MEC servers while considering constraints such as service caching, computation offloading, and the number of resources allocated. As the objective function is a complex problem, it is solved utilizing equivalent transformations and variations of the reduced constraints. A greedy algorithm is applied to solve the optimal function. A comparative experiment on resource allocation is conducted, and energy utilization parameters are calculated to compare the effectiveness of the proposed algorithm and the main algorithm. The results show that the proposed incentive mechanism has a significant advantage in improving the utility of the MEC server.