Show HTTP Headers

by 2/19/2010 11:42:00 AM 0 comments

Show HTTP Headers

Here's a little Groovy script to show the HTTP headers from a URL.
#!/usr/bin/env groovy

if (args.size() < 1) {
    println """
USAGE: 
  urlheaders.groovy  
  
ARGS:
  url = The URL to fetch headers from
  proxy = The proxy to go through. In the form of a column name:port. 
          For example "amoeba.ucsd.edu:9001"
    """
    System.exit(-1)
}

def url =  new URL(args[0])

def proxy = Proxy.NO_PROXY
if (args.size() > 1) {
    def proxyparts = args[1].split(":")
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyparts[0], proxyparts[1] as int))
}

url.openConnection(proxy).headerFields.each {key, value ->
    if (key) {
        print("${key}: ")
    }
    println("${value.join(",\n ")}")
}

and a Scala version (for Scala 2.8+):
#!/bin/sh
exec scala "$0" "$@"
!#

import java.net.{InetSocketAddress, Proxy, URL}
import scala.collection.JavaConversions._

def printer(key: String, value: Iterable[String]): Unit = {
    if (key != null) {
        print(key + ": ")
    }
    println(headers(key).reduceLeft(_ + ",\n " + _))
}

if (args.length < 1) {
    println("""
USAGE: 
  urlheaders.groovy  
  
ARGS:
  url = The URL to fetch headers from
  proxy = The proxy to go through. In the form of a column name:port. 
          For example "amoeba.ucsd.edu:9001"
    """)
    System.exit(-1)
}

val url = new URL(args(0))

var proxy = Proxy.NO_PROXY
if (args.length > 1) {
    val proxyparts = args(1).split(":")
    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyparts(0), proxyparts(1).toInt))
}
val connection = url.openConnection()
val headers = connection.getHeaderFields()

headers.keySet.foreach(key => printer(key, headers(key)))

hohonuuli

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

0 comments: