Search Results

Search found 7 results on 1 pages for 'httpbuilder'.

Page 1/1 | 1 

  • Interfacing HTTPBuilder and HTMLUnit... some code

    - by Misha Koshelev
    Ok, this isn't even a question: import com.gargoylesoftware.htmlunit.HttpMethod import com.gargoylesoftware.htmlunit.WebClient import com.gargoylesoftware.htmlunit.WebResponseData import com.gargoylesoftware.htmlunit.WebResponseImpl import com.gargoylesoftware.htmlunit.util.Cookie import com.gargoylesoftware.htmlunit.util.NameValuePair import static groovyx.net.http.ContentType.TEXT import java.io.File import java.util.logging.Logger import org.apache.http.impl.cookie.BasicClientCookie /** * HTTPBuilder class * * Allows Javascript processing using HTMLUnit * * @author Misha Koshelev */ class HTTPBuilder { /** * HTTP Builder - implement this way to avoid underlying logging output */ def httpBuilder /** * Logger */ def logger /** * Directory for storing HTML files, if any */ def saveDirectory=null /** * Index of current HTML file in directory */ def saveIdx=1 /** * Current page text */ def text=null /** * Response for processJavascript (Complex Version) */ def resp=null /** * URI for processJavascript (Complex Version) */ def uri=null /** * HttpMethod for processJavascript (Complex Version) */ def method=null /** * Default constructor */ public HTTPBuilder() { // New HTTPBuilder httpBuilder=new groovyx.net.http.HTTPBuilder() // Logging logger=Logger.getLogger(this.class.name) } /** * Constructor that allows saving output files for testing */ public HTTPBuilder(saveDirectory,saveIdx) { this() this.saveDirectory=saveDirectory this.saveIdx=saveIdx } /** * Save text and return corresponding XmlSlurper object */ public saveText() { if (saveDirectory) { def file=new File(saveDirectory.toString()+File.separator+saveIdx+".html") logger.finest "HTTPBuilder.saveText: file=\""+file.toString()+"\"" file<<text saveIdx++ } new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text) } /** * Wrapper around supertype get method */ public Object get(Map<String,?> args) { logger.finer "HTTPBuilder.get: args=\""+args+"\"" args.contentType=TEXT httpBuilder.get(args) { resp,reader-> text=reader.text this.resp=resp this.uri=args.uri this.method=HttpMethod.GET saveText() } } /** * Wrapper around supertype post method */ public Object post(Map<String,?> args) { logger.finer "HTTPBuilder.post: args=\""+args+"\"" args.contentType=TEXT httpBuilder.post(args) { resp,reader-> text=reader.text this.resp=resp this.uri=args.uri this.method=HttpMethod.POST saveText() } } /** * Load cookies from specified file */ def loadCookies(file) { logger.finer "HTTPBuilder.loadCookies: file=\""+file.toString()+"\"" file.withObjectInputStream { ois-> ois.readObject().each { cookieMap-> def cookie=new BasicClientCookie(cookieMap.name,cookieMap.value) cookieMap.remove("name") cookieMap.remove("value") cookieMap.entrySet().each { entry-> cookie."${entry.key}"=entry.value } httpBuilder.client.cookieStore.addCookie(cookie) } } } /** * Save cookies to specified file */ def saveCookies(file) { logger.finer "HTTPBuilder.saveCookies: file=\""+file.toString()+"\"" def cookieMaps=new ArrayList(new LinkedHashMap()) httpBuilder.client.cookieStore.getCookies().each { cookie-> def cookieMap=[:] cookieMap.version=cookie.version cookieMap.name=cookie.name cookieMap.value=cookie.value cookieMap.domain=cookie.domain cookieMap.path=cookie.path cookieMap.expiryDate=cookie.expiryDate cookieMaps.add(cookieMap) } file.withObjectOutputStream { oos-> oos.writeObject(cookieMaps) } } /** * Process Javascript using HTMLUnit (Simple Version) */ def processJavascript() { logger.finer "HTTPBuilder.processJavascript (Simple)" def webClient=new WebClient() def tempFile=File.createTempFile("HTMLUnit","") tempFile<<text def page=webClient.getPage("file://"+tempFile.toString()) webClient.waitForBackgroundJavaScript(10000) text=page.asXml() webClient.closeAllWindows() tempFile.delete() saveText() } /** * Process Javascript using HTMLUnit (Complex Version) * Closure, if specified, used to determine presence of necessary elements */ def processJavascript(closure) { logger.finer "HTTPBuilder.processJavascript (Complex)" // Convert response headers def headers=new ArrayList() resp.allHeaders.each() { header-> headers.add(new NameValuePair(header.name,header.value)) } def responseData=new WebResponseData(text.bytes,resp.statusLine.statusCode,resp.statusLine.toString(),headers) def response=new WebResponseImpl(responseData,uri.toURL(),method,0) // Transfer cookies def webClient=new WebClient() httpBuilder.client.cookieStore.getCookies().each { cookie-> webClient.cookieManager.addCookie(new Cookie(cookie.domain,cookie.name,cookie.value,cookie.path,cookie.expiryDate,cookie.isSecure())) } def page=webClient.loadWebResponseInto(response,webClient.getCurrentWindow()) // Wait for condition if (closure) { for (i in 1..20) { if (closure(page)) { break; } synchronized(page) { page.wait(500); } } } // Return text text=page.asXml() webClient.closeAllWindows() saveText() } } Allows one to interface HTTPBuilder with HTMLUnit! Enjoy Misha

    Read the article

  • POST with HTTPBuilder -> NullPointerException?

    - by Stefan Kendall
    I'm trying to make a simple HTTP POST request, and I have no idea why the following is failing. I tried following the examples here, and I don't see where I'm going wrong. Exception java.lang.NullPointerException at groovyx.net.http.HTTPBuilder$RequestConfigDelegate.setBody(HTTPBuilder.java:1131) ... Code def List<String> search(String query, int maxResults) { def http = new HTTPBuilder("mywebsite") http.request(POST) { uri.path = '/search/' body = [string1: "", query: "test"] requestContentType = URLENC headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4' response.success = { resp, InputStreamReader reader -> assert resp.statusLine.statusCode == 200 String data = reader.readLines().join() println data } } [] }

    Read the article

  • Convert cookies from HTMLUnit to HTTPBuilder?

    - by Misha Koshelev
    Dear All: I am doing this (in Groovy): def cookies=webClient.cookieManager.cookies def http=new HTTPBuilder("myurl") http.request(POST) { def headersCookie='' cookies.eachWithIndex() { cookie,i-> if (i>0) { headersCookie+='; ' } headersCookie+=cookie.getName()+"="+cookie.getValue() } headers.'Cookie'=headersCookie ... } Is there a better/less hacky way? Thank you Misha

    Read the article

  • HTTP Builder/Groovy - get source text _and_ XmlSlurper output?

    - by Misha Koshelev
    Dear All: I am reading here: http://groovy.codehaus.org/modules/http-builder/doc/get.html I seem to be able to get i) XMLSlurper output as parsed by NekoHTML using: def http = new HTTPBuilder('http://www.google.com') def html = http.get( path : '/search', query : [q:'Groovy'] ) ii) Raw text using: http.get( path : '/search', contentType : TEXT, query : [q:'Groovy'] ) { resp, reader -> println "response status: ${resp.statusLine}" println 'Headers: -----------' resp.headers.each { h -> println " ${h.name} : ${h.value}" } println 'Response data: -----' System.out << reader println '\n--------------------' } I am having some trouble and would like to get BOTH (i) and (ii) to debug my XmlSlurper code on the actual html I am getting. Any suggestions how I might go about doing this? I can easily instantiate an XmlSlurper object with the relevant string using the parseString(string) method or the parse(reader) method, but I cannot seem to get the Neko processing step correct. Any hints? Thank you! Misha

    Read the article

  • How does one save cookies in HTTP Builder 0.5.0/HTTPClient

    - by Misha Koshelev
    I am trying per instructions here: http://www.innovation.ch/java/HTTPClient/advanced_info.html However, if I am using HTTP Builder, the following lines System.setProperty("HTTPClient.cookies.save","true") System.setProperty("HTTPClient.cookies.jar","/home/misha/.httpclient_cookies") do not seem to create a file: ~/.httpclient_cookies I will post a solution as always when figure it out. :) Misha

    Read the article

  • HTTP Builder/Groovy - lost 302 (redirect) handling?

    - by Misha Koshelev
    Dear All: I am reading here http://groovy.codehaus.org/modules/http-builder/doc/handlers.html "In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses." This seems to work fine when I simply use the get() or post() methods without a closure. However, when I use a closure, I seem to lose 302 handling. Is there some way I can handle this myself? Thank you p.s. Here is my log output showing it is a 302 response [java] FINER: resp.statusLine: "HTTP/1.1 302 Found" Here is the relevant code: // Copyright (C) 2010 Misha Koshelev. All Rights Reserved. package com.mksoft.fbbday.main import groovyx.net.http.ContentType import java.util.logging.Level import java.util.logging.Logger class HTTPBuilder { def dataDirectory HTTPBuilder(dataDirectory) { this.dataDirectory=dataDirectory } // Main logic def logger=Logger.getLogger(this.class.name) def closure={resp,reader-> logger.finer("resp.statusLine: \"${resp.statusLine}\"") if (logger.isLoggable(Level.FINEST)) { def respHeadersString='Headers:'; resp.headers.each() { header->respHeadersString+="\n\t${header.name}=\"${header.value}\"" } logger.finest(respHeadersString) } def text=reader.text def lastHtml=new File("${dataDirectory}${File.separator}last.html") if (lastHtml.exists()) { lastHtml.delete() } lastHtml<<text new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(text) } def processArgs(args) { if (logger.isLoggable(Level.FINER)) { def argsString='Args:'; args.each() { arg->argsString+="\n\t${arg.key}=\"${arg.value}\"" } logger.finer(argsString) } args.contentType=groovyx.net.http.ContentType.TEXT args } // HTTPBuilder methods def httpBuilder=new groovyx.net.http.HTTPBuilder () def get(args) { httpBuilder.get(processArgs(args),closure) } def post(args) { args.contentType=groovyx.net.http.ContentType.TEXT httpBuilder.post(processArgs(args),closure) } } Here is a specific tester: #!/usr/bin/env groovy import groovyx.net.http.HTTPBuilder import groovyx.net.http.Method import static groovyx.net.http.ContentType.URLENC import java.util.logging.ConsoleHandler import java.util.logging.Level import java.util.logging.Logger // MUST ENTER VALID FACEBOOK EMAIL AND PASSWORD BELOW !!! def email='' def pass='' // Remove default loggers def logger=Logger.getLogger('') def handlers=logger.handlers handlers.each() { handler->logger.removeHandler(handler) } // Log ALL to Console logger.setLevel Level.ALL def consoleHandler=new ConsoleHandler() consoleHandler.setLevel Level.ALL logger.addHandler(consoleHandler) // Facebook - need to get main page to capture cookies def http = new HTTPBuilder() http.get(uri:'http://www.facebook.com') // Login def html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass]) assert html==null // Why null? html=http.post(uri:'https://login.facebook.com/login.php?login_attempt=1',body:[email:email,pass:pass]) { resp,reader-> assert resp.statusLine.statusCode==302 // Shouldn't we be redirected??? // http://groovy.codehaus.org/modules/http-builder/doc/handlers.html // "In cases where a response sends a redirect status code, this is handled internally by Apache HttpClient, which by default will simply follow the redirect by re-sending the request to the new URL. You do not need to do anything special in order to follow 302 responses. " } Here are relevant logs: FINE: Receiving response: HTTP/1.1 302 Found Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << HTTP/1.1 302 Found Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Expires: Sat, 01 Jan 2000 00:00:00 GMT Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Location: http://www.facebook.com/home.php? Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << P3P: CP="DSP LAW" Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Pragma: no-cache Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: datr=1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79; expires=Sun, 03-Jun-2012 21:37:24 GMT; path=/; domain=.facebook.com Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: lxe=koshelev%40post.harvard.edu; expires=Tue, 28-Sep-2010 15:24:04 GMT; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: lxr=deleted; expires=Thu, 04-Jun-2009 21:37:23 GMT; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Set-Cookie: pk=183883c0a9afab1608e95d59164cc7dd; path=/; domain=.facebook.com; httponly Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Content-Type: text/html; charset=utf-8 Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << X-Cnection: close Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Date: Fri, 04 Jun 2010 21:37:24 GMT Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.DefaultClientConnection receiveResponseHeader FINE: << Content-Length: 0 Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: datr][value: 1275687438-9ff6ae60a89d444d0fd9917abf56e085d370277a6e9ed50c1ba79][domain: .facebook.com][path: /][expiry: Sun Jun 03 16:37:24 CDT 2012]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: lxe][value: koshelev%40post.harvard.edu][domain: .facebook.com][path: /][expiry: Tue Sep 28 10:24:04 CDT 2010]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: lxr][value: deleted][domain: .facebook.com][path: /][expiry: Thu Jun 04 16:37:23 CDT 2009]". Jun 4, 2010 4:37:22 PM org.apache.http.client.protocol.ResponseProcessCookies processCookies FINE: Cookie accepted: "[version: 0][name: pk][value: 183883c0a9afab1608e95d59164cc7dd][domain: .facebook.com][path: /][expiry: null]". Jun 4, 2010 4:37:22 PM org.apache.http.impl.client.DefaultRequestDirector execute FINE: Connection can be kept alive indefinitely Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest FINE: Response code: 302; found handler: post302$_run_closure2@7023d08b Jun 4, 2010 4:37:22 PM groovyx.net.http.HTTPBuilder doRequest FINEST: response handler result: null Jun 4, 2010 4:37:22 PM org.apache.http.impl.conn.SingleClientConnManager releaseConnection FINE: Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter@605b28c9 You can see there is clearly a location argument. Thank you Misha

    Read the article

1