Mobile edge computing (MEC) has recently emerged to fulfill the computation demands of richer applications, and provide better experience for resource-hungry Internet-of-Things (IoT) devices at the edge of mobile networks. It is readily acknowledged that edge infrastructures are less capable of improving power usage efficiency (PUE) and integrating renewable energy. Besides, due to the limited battery capacities of IoT devices, the task execution would be interrupted when the battery runs out. Therefore, it is crucial to use green energy to prolong the battery life-time. Moreover, IoT devices can share computation and communication resources dynamically and beneficially among each other. Therefore, we develop an efficient task offloading strategy in order to improve PUE of edge server as well as achieving green computing. We also propose a green task offloading framework which leverages energy harvesting (EH) and device-to-device communication (D2D). Our framework aims at minimizing the long-term grid power energy consumption of edge server and cloud resource rental costs for task executions of all EH IoT devices. Meanwhile, the incentive constraints of preventing the over-exploiting behaviors should be considered, since they harm devices’ motivation for collaboration. To address the uncertain future system information, such as the availability of renewable energy, we resort to Lyapunov optimization technique to propose an online task offloading algorithm, in which the decisions only depend on system current state information. The implementation of this algorithm only requires to solve a deterministic problem in each time slot, for which the core idea is to transform the task offloading problem of each time slot into a graph matching problem and get the approximate optimal solution by calling Edmonds’s Blossom algorithm. Rigorous theoretical analysis and extensive evaluations demonstrate the superior performance of the proposed scheme.