Here is a very minimal groovy based Basic Authentication Client which can come handy whilst talking to APIs.
def jsonBody = '{"day" : "11", "month" : "03", "year" : "2010", "hour" : "09", "min" : "08", "lat" : "18.9750", "lon" : "72.8258", "tzone" : "5.5", "gender" : "male"}'
new BasicAuthClient(
userName:"xyzzy",
password:"ba4d90e133ad76b103fcedcd00ab5681",
address:"https://api.vedicrishiastro.com/v1/basic_panchang/"
).doPost(jsonBody)
class BasicAuthClient{
def userName, password, address, conn
def getAuthHeader(){
def authHeader = "$userName:$password".getBytes().encodeBase64().toString()
println(authHeader)
return authHeader
}
def getConnection(){
this.conn = address.toURL().openConnection()
conn.setDoOutput(true)
conn.setRequestMethod("POST")
conn.setRequestProperty("Authorization", "Basic ${getAuthHeader()}")
return conn
}
def doPost(body){
def out = getConnection().getOutputStream();
out.write(body.getBytes())
out.close();
return getResponse()
}
def getResponse(){
def responseCode = conn.getResponseCode();
println(responseCode)
def instream = responseCode < 207 ? conn.getInputStream() : conn.getErrorStream()
int i = instream.read()
while (i != -1) {
print((char)i)
i = instream.read()
}
instream.close()
conn.disconnect()
}
}
def jsonBody = '{"day" : "11", "month" : "03", "year" : "2010", "hour" : "09", "min" : "08", "lat" : "18.9750", "lon" : "72.8258", "tzone" : "5.5", "gender" : "male"}'
new BasicAuthClient(
userName:"xyzzy",
password:"ba4d90e133ad76b103fcedcd00ab5681",
address:"https://api.vedicrishiastro.com/v1/basic_panchang/"
).doPost(jsonBody)
class BasicAuthClient{
def userName, password, address, conn
def getAuthHeader(){
def authHeader = "$userName:$password".getBytes().encodeBase64().toString()
println(authHeader)
return authHeader
}
def getConnection(){
this.conn = address.toURL().openConnection()
conn.setDoOutput(true)
conn.setRequestMethod("POST")
conn.setRequestProperty("Authorization", "Basic ${getAuthHeader()}")
return conn
}
def doPost(body){
def out = getConnection().getOutputStream();
out.write(body.getBytes())
out.close();
return getResponse()
}
def getResponse(){
def responseCode = conn.getResponseCode();
println(responseCode)
def instream = responseCode < 207 ? conn.getInputStream() : conn.getErrorStream()
int i = instream.read()
while (i != -1) {
print((char)i)
i = instream.read()
}
instream.close()
conn.disconnect()
}
}