Praise be to Allah the Lord of the Worlds.
The Messenger of Allah (PBUH) has delivered the message of Islam and the teachings of Sharia from His Lord the Exalted to the fullest extent possible. Any apparent contradiction in his Hadiths (PBUH) was clarified and disambiguated by scholars. For example, the two Hadiths mentioned in the above question. The first Hadith addresses the general rules of lineage. In principle, a boy is attributed to the marriage bed and this is the ruling of Sharia. If the owner of the marriage bed was absolutely certain that the boy isn`t his, then he has the right to deny him through Li`an (invoking mutual curses), of course in accordance with its Sharia rules.
The second Hadith addresses the issue of sin. The Prophet (PBUH) said it to scare and deter women and show the prohibition and gravity of committing adultery. And Allah the Almighty knows best.