public string post_urlencoded(string url, string cookies, string postData) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); try { request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded;"; if (cookies != "") { request.Headers.Add("Cookie", cookies); } // 参数 StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding("EUC-KR")); writer.Write(postData); writer.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "EUC-KR"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); reader.Close(); reader.Dispose(); response.Close(); response.Dispose(); return retString; } catch (WebException ex) { HttpWebResponse response = (HttpWebResponse)ex.Response; StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("euc-kr")); string retString = reader.ReadToEnd(); return "error"; } finally { if (request != null) { request.Abort(); } } }改为python 语言
时间: 2024-01-18 07:02:35 浏览: 269
将上述C#代码改写为Python代码,如下所示:
```python
import http.client
import urllib.parse
def post_urlencoded(url, cookies, postData):
headers = {
'Content-type': 'application/x-www-form-urlencoded',
'Cookie': cookies
}
conn = http.client.HTTPConnection(url)
conn.request('POST', '', urllib.parse.urlencode(postData), headers)
response = conn.getresponse()
encoding = response.getheader('Content-Encoding', 'EUC-KR')
retString = response.read().decode(encoding)
conn.close()
return retString
```
注意,Python内置的`http.client`模块可以完成与C#中`HttpWebRequest`类似的HTTP请求操作。在发送POST请求时需要将请求数据进行URL编码,可以使用`urllib.parse.urlencode()`函数完成。同时,Python中的字符串默认使用Unicode编码,所以不需要进行字符编码转换。
阅读全文