Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala http operations

Tags:

How do I perform the following in Scala?

  • HTTP Get
  • HTTP Get With custom headers
  • HTTP Post
like image 892
Omry Yadan Avatar asked Apr 06 '11 09:04

Omry Yadan


People also ask

How does akka HTTP work?

The Akka HTTP modules implement a full server- and client-side HTTP stack on top of akka-actor and akka-stream . A typical application does not sit on top of Akka HTTP. Instead, Akka HTTP makes it easier to build integration layers based on HTTP, and therefore stays on the sidelines.

What are HTTP models?

Akka HTTP model contains a deeply structured, fully immutable, case-class based model of all the major HTTP data structures, like HTTP requests, responses and common headers. It lives in the akka-http-core module and forms the basis for most of Akka HTTP's APIs.

What is Scalaj HTTP?

Simplified Http. This is a fully featured http client for Scala which wraps java.net.HttpURLConnection. Features: Zero dependencies. Cross compiled for Scala 2.10, 2.11, 2.12, and 2.13-M3.

How do I use HttpRequest?

An HTTP request is made by a client, to a named host, which is located on a server. The aim of the request is to access a resource on the server. To make the request, the client uses components of a URL (Uniform Resource Locator), which includes the information needed to access the resource.


2 Answers

You could try out Dispatch. A little difficult to grasp at first, but after a while I've started to like it. It works on top of HttpClient.

import dispatch.Http
import Http._
// Get
Http(url("http://youruri.com/yo") >>> System.out)
// Get with header
Http(url("http://youruri.com/yo") <:< Map("Accept" -> "application/json") >>> System.out)
// Post
Http(url("http://youruri.com/yo") << yourPostData >|)
like image 86
thoredge Avatar answered Sep 17 '22 17:09

thoredge


You can simply use java.net.URL to send HTTP GET and HTTP POST requests. You can also set HTTP request headers on the HttpURLConnection like this:

val con = url.openConnection.asInstanceOf[HttpURLConnection]
con.setRequestProperty("Header", "Value")

I have written myself a utility class which does exactly this. You can see it here:

https://github.com/gruenewa/gruenewa-misc/blob/master/gruenewa-wsclient/src/main/scala/gruenewa/wsclient/Service.scala

like image 32
gruenewa Avatar answered Sep 18 '22 17:09

gruenewa