Refactor http connection code