我正在尝试构建网站搜寻器。 为此,我需要获取登录cookie。
我已经编写了以下Python代码,该代码为我获取了Cookie:
#!/usr/bin/python
import requests
import sys
from getpass import getpass
uname = sys.argv[1]
passw = getpass()
login = {"values[login]": uname, "values[password]": passw}
r = requests.post("https://redacted.com/signin/", data=login)
jar = r.history[0].cookies
token = jar['redacted-token']
with open("token", mode='w') as token_file:
token_file.write(token)
此代码通过python-requests库执行请求。
此代码是用Kotlin编写的,应该实现相同的目的:
import org.apache.http.NameValuePair
import org.apache.http.client.CookieStore
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.protocol.HttpClientContext
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
fun login(username: String, password: String, cookieStore: CookieStore) {
//Initialize http client
var httpclient = HttpClients.createDefault()
//Initialize http context
var context = HttpClientContext.create()
context.cookieStore = cookieStore
//Initialize Form
var formParams = arrayListOf<NameValuePair>()
formParams.add(BasicNameValuePair("values[login]", username))
formParams.add(BasicNameValuePair("values[password]", password))
var formEntity = UrlEncodedFormEntity(formParams)
//Initialize request
var httppost = HttpPost("https://redacted.com/signin/")
httppost.entity = formEntity //With form
var response = httpclient.execute(httppost, context)
print(EntityUtils.toString(httppost.entity))
print(EntityUtils.toString(response.entity))
}
服务器的响应表明密码和用户名错误。
我对这段代码的行为方式感到困惑。
有人可以帮我修复我的Kotlin代码吗?