以下Java http get请求的等效Python代码

时间:2015-03-09 16:20:20

标签: python httplib

我正在尝试将以下Java代码转换为Python。不确定我做错了什么,但我最终得到了一个内部服务器错误500与python。

"身体"在httplib.httpConnection方法中等效于Java httpentity? 什么可能是错的? 我收集的输入信息肯定是正确的。

任何帮助都将非常感激。我尝试了几件事,但最终却出现了相同的内部服务器错误。

Java代码:

HttpEntity reqEntitiy = new StringEntity("loginTicket="+ticket);
HttpRequestBase request = reMethod.getRequest(uri, reqEntitiy);
request.addHeader("ticket", ticket);
HttpResponse response = httpclient.execute(request);
HttpEntity responseEntity = response.getEntity();
StatusLine responseStatus = response.getStatusLine();

Python代码:

 url = serverURL + "resources/slmservices/templates/"+templateId+"/options"
#Create the request
ticket = ticket.replace("'",'"')
headers = {"ticket":ticket}
print "ticket",ticket

reqEntity = "loginTicket="+ticket
body = "loginTicket="+ticket


url2 = urlparse.urlparse(serverURL)
h1 = httplib.HTTPConnection(url2.hostname,8580)
print "h1",h1

url3 = urlparse.urlparse(url)
print "url path",url3.path
ubody = {"loginTicket":ticket}
data = urllib.urlencode(ubody)
conn = h1.request("GET",url3.path,data,headers)
#conn = h1.request("GET",url3.path)
response = h1.getresponse()
lines = response.read()
print "response.status",response.status
print "response.reason",response.reason

1 个答案:

答案 0 :(得分:0)

你不需要走这么低的水平。改为使用urllib2

import urllib2
from urllib import urlencode

url = "{}resources/slmservices/templates/{}/options".format(
    serverURL, templateId)
headers = {"ticket": ticket}
params = {"loginTicket": ticket}
url = '{}?{}'.format(url, urlencode(params))

request = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(request)
print 'Status', response.getcode()
print 'Response data', response.read()

请注意,参数会添加到 URL 以形成URL查询参数。

您可以通过安装requests library

来更简单地完成此操作
import requests

url = "{}resources/slmservices/templates/{}/options".format(
    serverURL, templateId)
headers = {"ticket": ticket}
params = {"loginTicket": ticket}

response = requests.get(url, params=params, headers=headers)
print 'Status', response.status
print 'Response data', response.content  # or response.text for Unicode

此处requests负责对URL查询字符串参数进行URL编码,并将其添加到URL中,就像Java一样。