Hier ist eine Klasse, an der ich gearbeitet habe. Es hat sowohl GET- als auch POST-Anforderungen. GET ohne Parameter - POST mit Parametern Ich habe es verwendet, um mit StreamSets zu kommunizieren, um eine Pipeline zu starten oder einen Pipeline-Status zu überprüfen.
Es benötigt nur die folgende Abhängigkeit in der Datei build.sbt:
libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.3.0"
Die Dokumentation finden Sie hier: https://github.com/scalaj/scalaj-http#post-raw-arraybyte-or-string-data-and-get-response-code
import scala.collection.mutable.ArrayBuffer
import scalaj.http.{Http, HttpResponse}
object HttpRequestHandler {
val userName: String = "admin"
val password: String = "admin"
def sendHttpGetRequest(request: String): String = {
println(" Send Http Get Request (Start) ")
try {
val httpResponse: HttpResponse[String] = Http(request).auth(userName,password)
.asString
val response = if (httpResponse.code == 200) httpResponse.body
else{
println("Bad HTTP response: code = "+httpResponse.code )
return "ERROR"
}
println(" Send Http Get Request (End) ")
return response
} catch {
case e: Exception => println("Error in sending Get request: "+e.getMessage)
return "ERROR"
}
}
def arrayBufferToJson(params:ArrayBuffer[(String,String)]): String ={
var jsonString = "{"
var count: Int = 0
for(param <- params){
jsonString+="\""+param._1+"\":\""+param._2+"\""+ ( if(count!=params.length-1) "," else "")
count+=1
}
jsonString+="}"
return jsonString
}
def sendHttpPostRequest(request: String,params: ArrayBuffer[(String,String)]): String = {
println(" Send Http Post Request (Start) ")
try {
val postData : String = arrayBufferToJson(params)
println("Parameters: "+postData)
val httpResponse: HttpResponse[String] = Http(request).auth(userName,password)
.header("X-Requested-By","sdc")
.header("Content-Type", "application/json;charset=UTF-8")
.header("X-Stream" , "true")
.header("Accept", "application/json")
.postData(postData.getBytes)
.asString
val response = if (httpResponse.code == 200) httpResponse.body
else{
println("Bad HTTP response: code = "+httpResponse.code )
"ERROR"
}
println(" Send Http Post Request (End) ")
return response
} catch {
case e: Exception => println("Error in sending Post request: " + e.getMessage)
return "ERROR"
}
}
}