org.apache.http.entity.ContentType Scala Examples
The following examples show how to use org.apache.http.entity.ContentType.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: Slack.scala From amadou with Apache License 2.0 | 5 votes |
package com.mediative.amadou import org.apache.http.client.methods.HttpPost import org.apache.http.entity.{ContentType, StringEntity} import org.apache.http.impl.client.HttpClients import org.json4s.NoTypeHints import org.json4s.jackson.Serialization import org.json4s.jackson.Serialization.{write} object Slack { case class PostException(msg: String) extends RuntimeException(msg) case class Payload( channel: String, text: String, username: String, icon_emoji: String, link_names: Boolean) } def post(message: String, icon: String = this.icon): Unit = { val payload = Payload(channel, message, user, icon, true) logger.info(s"Posting $payload to $url") val client = HttpClients.createDefault() val requestEntity = new StringEntity(write(payload), ContentType.APPLICATION_JSON) val postMethod = new HttpPost(url) postMethod.setEntity(requestEntity) val response = client.execute(postMethod) client.close() val status = response.getStatusLine if (status.getStatusCode != 200) throw PostException( s"$url replied with status ${status.getStatusCode}: ${status.getReasonPhrase}") } }
Example 2
Source File: HttpUtil.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.analytics.util import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import org.apache.http.HttpResponse import org.apache.http.client.methods.{HttpGet, HttpPost} import org.apache.http.client.{ClientProtocolException, ResponseHandler} import org.apache.http.entity.{ContentType, StringEntity} import org.apache.http.impl.client.{CloseableHttpClient, HttpClients} import org.apache.http.util.EntityUtils object HttpUtil { private val mapper = new ObjectMapper() private val responseHandler = new ResponseHandler[String]() { override def handleResponse(response: HttpResponse): String = { val status = response.getStatusLine.getStatusCode if (status >= 200 && status < 300) { val entity = response.getEntity if (entity != null) EntityUtils.toString(entity) else throw new ClientProtocolException("Unexpected null response") } else { throw new ClientProtocolException("Unexpected response status: " + status) } } } def get(url: String, client: CloseableHttpClient): String = { val httpGet = new HttpGet(url) client.execute(httpGet, responseHandler) } def get(url: String): String = { val client = HttpClients.createDefault try { get(url, client) } finally { client.close() } } def getJson(url: String): JsonNode = { val client = HttpClients.createDefault try { getJson(url, client) } finally { client.close() } } def getJson(url: String, client: CloseableHttpClient): JsonNode = { mapper.readTree(get(url, client)) } def getJson(url: String, content: String, contentType: String): JsonNode = { val httpPost = new HttpPost(url) val entity = new StringEntity(content, ContentType.create(contentType, "UTF-8")) httpPost.setEntity(entity) val client = HttpClients.createDefault try { mapper.readTree(client.execute(httpPost, responseHandler)) } finally { client.close() } } }
Example 3
Source File: HttpRequestHandler.scala From sparklens with Apache License 2.0 | 5 votes |
package com.qubole.sparklens.helper import org.apache.http.client.methods.RequestBuilder import org.apache.http.entity.ContentType import org.apache.http.entity.mime.HttpMultipartMode import org.apache.http.entity.mime.MultipartEntityBuilder import org.apache.http.impl.client.HttpClients import java.io.File import org.apache.http.HttpResponse object HttpRequestHandler { def requestReport(fileName: String, email: String): HttpResponse = { val httpclient = HttpClients.createDefault() val file = new File(fileName) val builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("file-2", file, ContentType.DEFAULT_BINARY, file.getName()) .addTextBody("email", email) val postData = builder.build() val request = RequestBuilder .post("http://sparklens.qubole.com/generate_report/request_generate_report") .setEntity(postData) .build() val response = httpclient.execute(request) response } }
Example 4
Source File: Http.scala From seed with Apache License 2.0 | 5 votes |
package seed.publish.util import java.net.URI import org.apache.commons.io.IOUtils import org.apache.http.{HttpHost, HttpRequest, HttpRequestInterceptor} import org.apache.http.entity.ContentType import seed.util.ZioHelpers._ import zio.Task import org.apache.http.auth.AuthScope import org.apache.http.auth.UsernamePasswordCredentials import org.apache.http.client.protocol.HttpClientContext import org.apache.http.impl.auth.BasicScheme import org.apache.http.impl.client.{BasicAuthCache, BasicCredentialsProvider} import org.apache.http.impl.nio.client.CloseableHttpAsyncClient import org.apache.http.impl.nio.client.HttpAsyncClients import org.apache.http.nio.client.methods.HttpAsyncMethods import org.apache.http.nio.protocol.HttpAsyncRequestProducer import org.apache.http.protocol.HttpContext class Http(httpClient: CloseableHttpAsyncClient) { def put(url: String, bytes: Array[Byte]): Task[String] = { val producer = HttpAsyncMethods.createPut(url, bytes, ContentType.DEFAULT_BINARY) send(url, producer) } def post(url: String, bytes: Array[Byte]): Task[String] = { val producer = HttpAsyncMethods.createPost(url, bytes, ContentType.DEFAULT_BINARY) send(url, producer) } def destroy(): Unit = httpClient.close() private def send(url: String, producer: HttpAsyncRequestProducer) = { val client = new CompletableHttpAsyncClient(httpClient) val uri = URI.create(url) val targetHost = new HttpHost(uri.getHost, uri.getPort, uri.getScheme) val authCache = new BasicAuthCache() authCache.put(targetHost, new BasicScheme()) val clientContext = HttpClientContext.create() clientContext.setAuthCache(authCache) val future = client.execute(producer, HttpAsyncMethods.createConsumer(), clientContext) fromCompletableFuture(future) .map(r => IOUtils.toString(r.getEntity.getContent, "UTF-8")) } } class CustomRequestInterceptor(log: seed.Log) extends HttpRequestInterceptor { override def process(request: HttpRequest, context: HttpContext): Unit = log.debug("Sending HTTP request " + request + "...") } object Http { def create(log: seed.Log, authHost: String, auth: (String, String)): Http = { val credsProvider = new BasicCredentialsProvider() credsProvider.setCredentials( new AuthScope(authHost, 443), new UsernamePasswordCredentials(auth._1, auth._2) ) val c = HttpAsyncClients .custom() .setDefaultCredentialsProvider(credsProvider) .addInterceptorFirst(new CustomRequestInterceptor(log)) .build() c.start() new Http(c) } }
Example 5
Source File: HttpExecutionTest.scala From maze with Apache License 2.0 | 5 votes |
package fr.vsct.dt.maze.helpers import com.typesafe.scalalogging.StrictLogging import fr.vsct.dt.maze.core.Commands.expectThat import fr.vsct.dt.maze.core.Predef._ import fr.vsct.dt.maze.core.{Predicate, Result} import org.apache.http._ import org.apache.http.client.methods.{CloseableHttpResponse, HttpGet} import org.apache.http.entity.{ContentType, StringEntity} import org.apache.http.impl.client.CloseableHttpClient import org.apache.http.message.{BasicHttpResponse, BasicStatusLine} import org.apache.http.protocol.HttpContext import org.scalatest.FlatSpec import scala.beans.BeanProperty class HttpExecutionTest extends FlatSpec { class MockHttpClient(val response: String) extends CloseableHttpClient with StrictLogging { var init = false override def doExecute(target: HttpHost, request: HttpRequest, context: HttpContext): CloseableHttpResponse = { if (!init) throw new IllegalStateException("Client is not initialized") logger.info("Doing actual http call") val r = if(request.getRequestLine.getUri == "http://some-url.com") { val t = new BasicCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK")) t.setEntity(new StringEntity(response, "UTF-8")) t } else { val t = new BasicCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_BAD_REQUEST, "KO")) t.setEntity(new StringEntity("""{"status": "ko"}""", ContentType.APPLICATION_JSON)) t } r } @Deprecated override def getConnectionManager = null @Deprecated override def getParams = null override def close(): Unit = {} class BasicCloseableHttpResponse(statusLine: StatusLine) extends BasicHttpResponse(statusLine) with CloseableHttpResponse { override def close(): Unit = {} } } "a http check" should "not do an effective call until apply is effectively called" in { Http.client = new MockHttpClient("Youppy !") val requestOk = new HttpGet("http://some-url.com") val check1: Predicate = Http.execute(requestOk).status is 200 val check2: Predicate = Http.execute(requestOk).response is "Youppy !" val check3 = check1 || check2 val check4 = !check3 Http.client.asInstanceOf[MockHttpClient].init = true assert(check1.get() == Result.success) assert(check2.get() == Result.success) assert(check3.get() == Result.success) assert(check4.get() == Result.failure(s"Expected ${check3.label} to be false")) expectThat(Http.get("http://some-error-url.com").status is 400) expectThat(Http.get("http://some-url.com").isOk) expectThat(!Http.get("http://some-error-url.com").isOk) expectThat(Http.get("http://some-error-url.com").responseAs(classOf[Stupid]) is Stupid(status = "ko")) } } case class Stupid(@BeanProperty status: String)
Example 6
Source File: PagerDutyEventApi.scala From sumobot with Apache License 2.0 | 5 votes |
package com.sumologic.sumobot.plugins.pagerduty import com.sumologic.sumobot.plugins.HttpClientWithTimeOut import org.apache.http.client.methods.HttpPost import org.apache.http.entity.{ContentType, StringEntity} import play.api.libs.json.Json class PagerDutyEventApi { case class PagerDutyEvent(service_key: String, event_type: String, incident_key: String, description: String) implicit val pagerDutyEventFormat = Json.format[PagerDutyEvent] private val SubmitUrl = "https://events.pagerduty.com/generic/2010-04-15/create_event.json" private val client = HttpClientWithTimeOut.client() def page(channel: String, serviceKey: String, description: String) { val event = Json.toJson(PagerDutyEvent(serviceKey, "trigger", channel, description)) val entity = new StringEntity(event.toString(), ContentType.APPLICATION_JSON) val post = new HttpPost(SubmitUrl) post.setEntity(entity) client.execute(post) } }