We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
httplib exceptions
Running my bot continuously, I sometimes get rare exceptions. This traceback was with Python 2.7  and python-telegram-bot 3.2:

```
  File "/home/rahiel/BismillahBot/bismillah.py", line 99, in send_quran  
    bot.sendMessage(chat_id=chat_id, text=text)
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py", line 127, in decorator  
    result = func(self, *args, **kwargs)  
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py", line 159, in decorator  
    result = request.post(url, data)  
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py", line 67, in decorator  
    return func(*args, **kwargs)  
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py", line 140, in post  
    result = urlopen(request, timeout=timeout).read()  
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen  
    return _opener.open(url, data, timeout)  
  File "/usr/lib/python2.7/urllib2.py", line 404, in open  
    response = self._open(req, data)  
  File "/usr/lib/python2.7/urllib2.py", line 422, in _open  
    '_open', req)  
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain  
    result = func(*args)  
  File "/usr/lib/python2.7/urllib2.py", line 1222, in https_open  
    return self.do_open(httplib.HTTPSConnection, req)  
  File "/usr/lib/python2.7/urllib2.py", line 1187, in do_open  
    r = h.getresponse(buffering=True)  
  File "/usr/lib/python2.7/httplib.py", line 1051, in getresponse  
    response.begin()  
  File "/usr/lib/python2.7/httplib.py", line 415, in begin  
    version, status, reason = self._read_status()  
  File "/usr/lib/python2.7/httplib.py", line 379, in _read_status  
    raise BadStatusLine(line)  
httplib.BadStatusLine: ''  
```

Using version 2.9 of the library I got this traceback in the past:

```
  File "/home/rahiel/BismillahBot/bismillah.py", line 122, in upload
    v = bot.sendAudio(audio=f, **kwargs)["audio"]["file_id"]
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py", line 126, in decorator
    result = func(self, *args, **kwargs)
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py", line 158, in decorator
    result = request.post(url, data)
  File "/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py", line 108, in post
    message = _parse(error.read())
  File "/usr/lib/python2.7/socket.py", line 351, in read
    data = self._sock.recv(rbufsize)
  File "/usr/lib/python2.7/httplib.py", line 549, in read
    return self._read_chunked(amt)
  File "/usr/lib/python2.7/httplib.py", line 603, in _read_chunked
    raise IncompleteRead(''.join(value))
httplib.IncompleteRead: IncompleteRead(0 bytes read)
```

Maybe we should catch these exceptions and reraise them as a TelegramError for http errors? I was puzzled by the second traceback, because I was getting it frequently, but that stopped since I updated the library.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `telegram/utils/request.py`
Content:
```
1 #!/usr/bin/env python
2 # pylint: disable=no-name-in-module,unused-import
3 #
4 # A library that provides a Python interface to the Telegram Bot API
5 # Copyright (C) 2015-2016
6 # Leandro Toledo de Souza <devs@python-telegram-bot.org>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Lesser Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU Lesser Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser Public License
19 # along with this program.  If not, see [http://www.gnu.org/licenses/].
20 
21 """This module contains methods to make POST and GET requests"""
22 
23 import functools
24 import json
25 import socket
26 from ssl import SSLError
27 
28 try:
29     from urllib.request import urlopen, urlretrieve, Request
30     from urllib.error import HTTPError
31 except ImportError:
32     from urllib import urlretrieve
33     from urllib2 import urlopen, Request
34     from urllib2 import HTTPError
35 
36 from telegram import (InputFile, TelegramError)
37 
38 
39 def _parse(json_data):
40     """Try and parse the JSON returned from Telegram and return an empty
41     dictionary if there is any error.
42 
43     Args:
44       url:
45         urllib.urlopen object
46 
47     Returns:
48       A JSON parsed as Python dict with results.
49     """
50     decoded_s = json_data.decode('utf-8')
51     try:
52         data = json.loads(decoded_s)
53     except ValueError:
54         raise TelegramError('Invalid server response')
55 
56     if not data.get('ok') and data.get('description'):
57         return data['description']
58 
59     return data['result']
60 
61 
62 def _try_except_req(func):
63     """Decorator for requests to handle known exceptions"""
64     @functools.wraps(func)
65     def decorator(*args, **kwargs):
66         try:
67             return func(*args, **kwargs)
68         except HTTPError as error:
69             if error.getcode() == 403:
70                 raise TelegramError('Unauthorized')
71             if error.getcode() == 502:
72                 raise TelegramError('Bad Gateway')
73 
74             try:
75                 message = _parse(error.read())
76             except ValueError:
77                 message = 'Unknown HTTPError {0}'.format(error.getcode())
78 
79             raise TelegramError(message)
80         except (SSLError, socket.timeout) as error:
81             if "operation timed out" in str(error):
82                 raise TelegramError("Timed out")
83 
84             raise TelegramError(str(error))
85 
86     return decorator
87 
88 
89 @_try_except_req
90 def get(url):
91     """Request an URL.
92     Args:
93       url:
94         The web location we want to retrieve.
95 
96     Returns:
97       A JSON object.
98     """
99     result = urlopen(url).read()
100 
101     return _parse(result)
102 
103 
104 @_try_except_req
105 def post(url,
106          data,
107          network_delay=2.):
108     """Request an URL.
109     Args:
110       url:
111         The web location we want to retrieve.
112       data:
113         A dict of (str, unicode) key/value pairs.
114       network_delay:
115         Additional timeout in seconds to allow the response from Telegram to
116         take some time.
117 
118     Returns:
119       A JSON object.
120     """
121 
122     # Add time to the timeout of urlopen to allow data to be transferred over
123     # the network.
124     if 'timeout' in data:
125         timeout = data['timeout'] + network_delay
126     else:
127         timeout = None
128 
129     if InputFile.is_inputfile(data):
130         data = InputFile(data)
131         request = Request(url,
132                           data=data.to_form(),
133                           headers=data.headers)
134     else:
135         data = json.dumps(data)
136         request = Request(url,
137                           data=data.encode(),
138                           headers={'Content-Type': 'application/json'})
139 
140     result = urlopen(request, timeout=timeout).read()
141     return _parse(result)
142 
143 
144 @_try_except_req
145 def download(url,
146              filename):
147     """Download a file by its URL.
148     Args:
149       url:
150         The web location we want to retrieve.
151 
152       filename:
153         The filename wihtin the path to download the file.
154     """
155 
156     urlretrieve(url, filename)
157
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/telegram/utils/request.py b/telegram/utils/request.py
--- a/telegram/utils/request.py
+++ b/telegram/utils/request.py
@@ -25,6 +25,13 @@
 import socket
 from ssl import SSLError
 
+try:
+    # python2
+    from httplib import HTTPException
+except ImportError:
+    # python3
+    from http.client import HTTPException
+
 try:
     from urllib.request import urlopen, urlretrieve, Request
     from urllib.error import HTTPError
@@ -82,6 +89,8 @@
                 raise TelegramError("Timed out")
 
             raise TelegramError(str(error))
+        except HTTPException as error:
+            raise TelegramError('HTTPException: {0!r}'.format(error))
 
     return decorator

{"golden_diff": "diff --git a/telegram/utils/request.py b/telegram/utils/request.py\n--- a/telegram/utils/request.py\n+++ b/telegram/utils/request.py\n@@ -25,6 +25,13 @@\n import socket\n from ssl import SSLError\n \n+try:\n+    # python2\n+    from httplib import HTTPException\n+except ImportError:\n+    # python3\n+    from http.client import HTTPException\n+\n try:\n     from urllib.request import urlopen, urlretrieve, Request\n     from urllib.error import HTTPError\n@@ -82,6 +89,8 @@\n                 raise TelegramError(\"Timed out\")\n \n             raise TelegramError(str(error))\n+        except HTTPException as error:\n+            raise TelegramError('HTTPException: {0!r}'.format(error))\n \n     return decorator\n", "issue": "httplib exceptions\nRunning my bot continuously, I sometimes get rare exceptions. This traceback was with Python 2.7  and python-telegram-bot 3.2:\n\n```\n  File \"/home/rahiel/BismillahBot/bismillah.py\", line 99, in send_quran  \n    bot.sendMessage(chat_id=chat_id, text=text)\n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py\", line 127, in decorator  \n    result = func(self, *args, **kwargs)  \n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py\", line 159, in decorator  \n    result = request.post(url, data)  \n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py\", line 67, in decorator  \n    return func(*args, **kwargs)  \n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py\", line 140, in post  \n    result = urlopen(request, timeout=timeout).read()  \n  File \"/usr/lib/python2.7/urllib2.py\", line 127, in urlopen  \n    return _opener.open(url, data, timeout)  \n  File \"/usr/lib/python2.7/urllib2.py\", line 404, in open  \n    response = self._open(req, data)  \n  File \"/usr/lib/python2.7/urllib2.py\", line 422, in _open  \n    '_open', req)  \n  File \"/usr/lib/python2.7/urllib2.py\", line 382, in _call_chain  \n    result = func(*args)  \n  File \"/usr/lib/python2.7/urllib2.py\", line 1222, in https_open  \n    return self.do_open(httplib.HTTPSConnection, req)  \n  File \"/usr/lib/python2.7/urllib2.py\", line 1187, in do_open  \n    r = h.getresponse(buffering=True)  \n  File \"/usr/lib/python2.7/httplib.py\", line 1051, in getresponse  \n    response.begin()  \n  File \"/usr/lib/python2.7/httplib.py\", line 415, in begin  \n    version, status, reason = self._read_status()  \n  File \"/usr/lib/python2.7/httplib.py\", line 379, in _read_status  \n    raise BadStatusLine(line)  \nhttplib.BadStatusLine: ''  \n```\n\nUsing version 2.9 of the library I got this traceback in the past:\n\n```\n  File \"/home/rahiel/BismillahBot/bismillah.py\", line 122, in upload\n    v = bot.sendAudio(audio=f, **kwargs)[\"audio\"][\"file_id\"]\n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py\", line 126, in decorator\n    result = func(self, *args, **kwargs)\n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/bot.py\", line 158, in decorator\n    result = request.post(url, data)\n  File \"/home/rahiel/BismillahBot/venv/local/lib/python2.7/site-packages/telegram/utils/request.py\", line 108, in post\n    message = _parse(error.read())\n  File \"/usr/lib/python2.7/socket.py\", line 351, in read\n    data = self._sock.recv(rbufsize)\n  File \"/usr/lib/python2.7/httplib.py\", line 549, in read\n    return self._read_chunked(amt)\n  File \"/usr/lib/python2.7/httplib.py\", line 603, in _read_chunked\n    raise IncompleteRead(''.join(value))\nhttplib.IncompleteRead: IncompleteRead(0 bytes read)\n```\n\nMaybe we should catch these exceptions and reraise them as a TelegramError for http errors? I was puzzled by the second traceback, because I was getting it frequently, but that stopped since I updated the library.\n\n", "before_files": [{"content": "#!/usr/bin/env python\n# pylint: disable=no-name-in-module,unused-import\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2016\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\n\n\"\"\"This module contains methods to make POST and GET requests\"\"\"\n\nimport functools\nimport json\nimport socket\nfrom ssl import SSLError\n\ntry:\n    from urllib.request import urlopen, urlretrieve, Request\n    from urllib.error import HTTPError\nexcept ImportError:\n    from urllib import urlretrieve\n    from urllib2 import urlopen, Request\n    from urllib2 import HTTPError\n\nfrom telegram import (InputFile, TelegramError)\n\n\ndef _parse(json_data):\n    \"\"\"Try and parse the JSON returned from Telegram and return an empty\n    dictionary if there is any error.\n\n    Args:\n      url:\n        urllib.urlopen object\n\n    Returns:\n      A JSON parsed as Python dict with results.\n    \"\"\"\n    decoded_s = json_data.decode('utf-8')\n    try:\n        data = json.loads(decoded_s)\n    except ValueError:\n        raise TelegramError('Invalid server response')\n\n    if not data.get('ok') and data.get('description'):\n        return data['description']\n\n    return data['result']\n\n\ndef _try_except_req(func):\n    \"\"\"Decorator for requests to handle known exceptions\"\"\"\n    @functools.wraps(func)\n    def decorator(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except HTTPError as error:\n            if error.getcode() == 403:\n                raise TelegramError('Unauthorized')\n            if error.getcode() == 502:\n                raise TelegramError('Bad Gateway')\n\n            try:\n                message = _parse(error.read())\n            except ValueError:\n                message = 'Unknown HTTPError {0}'.format(error.getcode())\n\n            raise TelegramError(message)\n        except (SSLError, socket.timeout) as error:\n            if \"operation timed out\" in str(error):\n                raise TelegramError(\"Timed out\")\n\n            raise TelegramError(str(error))\n\n    return decorator\n\n\n@_try_except_req\ndef get(url):\n    \"\"\"Request an URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n\n    Returns:\n      A JSON object.\n    \"\"\"\n    result = urlopen(url).read()\n\n    return _parse(result)\n\n\n@_try_except_req\ndef post(url,\n         data,\n         network_delay=2.):\n    \"\"\"Request an URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n      data:\n        A dict of (str, unicode) key/value pairs.\n      network_delay:\n        Additional timeout in seconds to allow the response from Telegram to\n        take some time.\n\n    Returns:\n      A JSON object.\n    \"\"\"\n\n    # Add time to the timeout of urlopen to allow data to be transferred over\n    # the network.\n    if 'timeout' in data:\n        timeout = data['timeout'] + network_delay\n    else:\n        timeout = None\n\n    if InputFile.is_inputfile(data):\n        data = InputFile(data)\n        request = Request(url,\n                          data=data.to_form(),\n                          headers=data.headers)\n    else:\n        data = json.dumps(data)\n        request = Request(url,\n                          data=data.encode(),\n                          headers={'Content-Type': 'application/json'})\n\n    result = urlopen(request, timeout=timeout).read()\n    return _parse(result)\n\n\n@_try_except_req\ndef download(url,\n             filename):\n    \"\"\"Download a file by its URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n\n      filename:\n        The filename wihtin the path to download the file.\n    \"\"\"\n\n    urlretrieve(url, filename)\n", "path": "telegram/utils/request.py"}], "after_files": [{"content": "#!/usr/bin/env python\n# pylint: disable=no-name-in-module,unused-import\n#\n# A library that provides a Python interface to the Telegram Bot API\n# Copyright (C) 2015-2016\n# Leandro Toledo de Souza <devs@python-telegram-bot.org>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Lesser Public License for more details.\n#\n# You should have received a copy of the GNU Lesser Public License\n# along with this program.  If not, see [http://www.gnu.org/licenses/].\n\n\"\"\"This module contains methods to make POST and GET requests\"\"\"\n\nimport functools\nimport json\nimport socket\nfrom ssl import SSLError\n\ntry:\n    # python2\n    from httplib import HTTPException\nexcept ImportError:\n    # python3\n    from http.client import HTTPException\n\ntry:\n    from urllib.request import urlopen, urlretrieve, Request\n    from urllib.error import HTTPError\nexcept ImportError:\n    from urllib import urlretrieve\n    from urllib2 import urlopen, Request\n    from urllib2 import HTTPError\n\nfrom telegram import (InputFile, TelegramError)\n\n\ndef _parse(json_data):\n    \"\"\"Try and parse the JSON returned from Telegram and return an empty\n    dictionary if there is any error.\n\n    Args:\n      url:\n        urllib.urlopen object\n\n    Returns:\n      A JSON parsed as Python dict with results.\n    \"\"\"\n    decoded_s = json_data.decode('utf-8')\n    try:\n        data = json.loads(decoded_s)\n    except ValueError:\n        raise TelegramError('Invalid server response')\n\n    if not data.get('ok') and data.get('description'):\n        return data['description']\n\n    return data['result']\n\n\ndef _try_except_req(func):\n    \"\"\"Decorator for requests to handle known exceptions\"\"\"\n    @functools.wraps(func)\n    def decorator(*args, **kwargs):\n        try:\n            return func(*args, **kwargs)\n        except HTTPError as error:\n            if error.getcode() == 403:\n                raise TelegramError('Unauthorized')\n            if error.getcode() == 502:\n                raise TelegramError('Bad Gateway')\n\n            try:\n                message = _parse(error.read())\n            except ValueError:\n                message = 'Unknown HTTPError {0}'.format(error.getcode())\n\n            raise TelegramError(message)\n        except (SSLError, socket.timeout) as error:\n            if \"operation timed out\" in str(error):\n                raise TelegramError(\"Timed out\")\n\n            raise TelegramError(str(error))\n        except HTTPException as error:\n            raise TelegramError('HTTPException: {0!r}'.format(error))\n\n    return decorator\n\n\n@_try_except_req\ndef get(url):\n    \"\"\"Request an URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n\n    Returns:\n      A JSON object.\n    \"\"\"\n    result = urlopen(url).read()\n\n    return _parse(result)\n\n\n@_try_except_req\ndef post(url,\n         data,\n         network_delay=2.):\n    \"\"\"Request an URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n      data:\n        A dict of (str, unicode) key/value pairs.\n      network_delay:\n        Additional timeout in seconds to allow the response from Telegram to\n        take some time.\n\n    Returns:\n      A JSON object.\n    \"\"\"\n\n    # Add time to the timeout of urlopen to allow data to be transferred over\n    # the network.\n    if 'timeout' in data:\n        timeout = data['timeout'] + network_delay\n    else:\n        timeout = None\n\n    if InputFile.is_inputfile(data):\n        data = InputFile(data)\n        request = Request(url,\n                          data=data.to_form(),\n                          headers=data.headers)\n    else:\n        data = json.dumps(data)\n        request = Request(url,\n                          data=data.encode(),\n                          headers={'Content-Type': 'application/json'})\n\n    result = urlopen(request, timeout=timeout).read()\n    return _parse(result)\n\n\n@_try_except_req\ndef download(url,\n             filename):\n    \"\"\"Download a file by its URL.\n    Args:\n      url:\n        The web location we want to retrieve.\n\n      filename:\n        The filename wihtin the path to download the file.\n    \"\"\"\n\n    urlretrieve(url, filename)\n", "path": "telegram/utils/request.py"}]}