我在使用wget时获取cookie但在使用groovy脚本时没有cookie

时间:2016-03-28 20:07:33

标签: http groovy

这是wget命令:

static List<String> login(String baseUrl, String path, query, method = Method.POST) {
        try {
            def ret = null
            def http = new HTTPBuilder(baseUrl)

            http.request(method, ContentType.URLENC) {
            uri.path = path
            uri.query = query

            headers.'Authorization' = "Basic ${"auth_user:auth_pass".bytes.encodeBase64().toString()}"

            // response handler for a success response code
            response.success = { resp, data ->    

                println "response status: ${resp.statusLine}"

                resp.getHeaders('Set-Cookie').each {

                    def cookie = it.value.split(";").toString()
                    println cookie
                    .add(cookie)
                }
                println 'Response : ' + resp.getData()
            }
         }
         return cookies

        } catch (groovyx.net.http.HttpResponseException ex) {
            ex.printStackTrace()

        } catch (java.net.ConnectException ex) {
            ex.printStackTrace()

        }
    }

def url = "https://www.helloworld.com/login.php"
def path = ""
def query = [ user_login: "username@calypso", pass: "password" ]

// Submit a request via POST
def response = login(url, path, query)

这是groovy脚本:

response status: HTTP/1.1 200 OK
Header:
 Date : Mon, 28 Mar 2016 19:56:20 GMT
 Server : Apache/2.2.3 (CentOS)
 Last-Modified : Sat, 03 May 2003 21:37:01 GMT
 ETag : "56b0013-1d4-3bcc9546cd940"
 Accept-Ranges : bytes
 Content-Length : 468
 Keep-Alive : timeout=999
 Connection : Keep-Alive
 Content-Type : text/html; charset=UTF-8

所以wget命令让我得到cookie,但这个groovy脚本没有。这是我得到的回应:

Section

3 个答案:

答案 0 :(得分:1)

您可能不应该自己进行身份验证。如果只有成功的身份验证创建了cookie,这可以解释这种现象。

尝试

def http = new HTTPBuilder(baseUrl)
http.auth.basic 'auth_user', 'auth_pass'

另见documentation。此外,非空响应机构可能会给你一个关于出错的提示。

答案 1 :(得分:0)

我认为问题在于你在分割后调用了数组上的toString。尝试获取数组的第一个值:

String cookie = it.value.split(';')[0]

答案 2 :(得分:0)

cookie是否可能是httpOnly而你的groovy脚本是否尊重它,但wget不是?