本文整理汇总了Scala中org.apache.http.client.methods.HttpPost类的典型用法代码示例。如果您正苦于以下问题:Scala HttpPost类的具体用法?Scala HttpPost怎么用?Scala HttpPost使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HttpPost类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: Item
//设置package包名称以及导入依赖的类
package com.github.vladminzatu.surfer.persist
import com.github.vladminzatu.surfer.Score
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.{HttpClientBuilder}
import org.apache.spark.rdd.RDD
import org.json4s.jackson.Serialization.write
case class Item(item:String, score:Double)
class RestPersister extends Persister {
val url = "http://localhost:8080/items"
override def persist(scores: RDD[(String, Score)]): Unit = {
implicit val formats = org.json4s.DefaultFormats
val payload = write(scores.collect().sortWith((a,b) => a._2.value > b._2.value).map(x => Item(x._1, x._2.value)))
val client = HttpClientBuilder.create().build();
client.execute(postRequest(payload))
}
private def postRequest(payload: String): HttpPost = {
val post = new HttpPost(url)
post.setEntity(new StringEntity(payload))
post
}
}
示例2: CinepolisHTTP
//设置package包名称以及导入依赖的类
package com.rho.scrap
object CinepolisHTTP {
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.DefaultHttpClient
import com.rho.client.RhoClient
import com.rho.scrap.CinepolisParse.{parseZones,parseCinemas,parseComplex}
import com.rho.scrap.CinepolisClasses.{Cinema,Complex}
val scheme = "http"
val host = "www.cinepolis.com"
val client = new RhoClient(Scheme=scheme,Host=host)
val optionsPath = "/cartelera/cdmx-centro/"
val cinemasPath = "/Cartelera.aspx/GetNowPlayingByCity"
val complexPath = "/Cartelera.aspx/ObtenerInformacionComplejo"
val prefix = "[HTTP] "
def getZones: List[String] = {
System.out.println(prefix+"Fetching zone list")
val list = parseZones(client.doGET(Map(),optionsPath))
System.out.println(prefix+"Done")
list
}
private def constructPOST(json: String, path: String): HttpPost = {
val post = new HttpPost(scheme+"://"+host+path)
post.setHeader("content-type", "application/json")
post.setEntity(new StringEntity(json))
post
}
def getCinemas(zone: String): List[Cinema] = {
val json = "{\"claveCiudad\":\""+zone+"\",\"esVIP\":false}"
val post = constructPOST(json, cinemasPath)
System.out.println(prefix+"Fetching Cinemas for zone "+zone)
val body = client.doRequest(post)
System.out.println(prefix+"Done")
parseCinemas(body)
}
def getComplex(cinema: Cinema): Complex = {
val json = "{\"idComplejo\":"+cinema.Id+",\"HijosComplejo\":\"\"}"
val post = constructPOST(json, complexPath)
System.out.println(prefix+"Fetching complex for "+cinema.Id+": "+cinema.Name)
val body = client.doRequest(post)
System.out.println(prefix+"Done")
parseComplex(body)
}
}
示例3: ProvisionUser
//设置package包名称以及导入依赖的类
// Copyright (c) 2017 Grier Forensics. All Rights Reserved.
package com.grierforensics.greatdane.connector
import java.net.URI
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.apache.commons.io.IOUtils
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
object ProvisionUser {
def main(args: Array[String]): Unit = {
def die = {
println("Usage: provision-user <email-address> [<certificate file>]")
sys.exit(1)
}
val (emailAddress, certPem) = args.toList match {
case email :: tail => tail match {
case Nil => (email, "")
case certFile :: Nil => (email, new String(Files.readAllBytes(Paths.get(certFile)), StandardCharsets.UTF_8))
case _ => die
}
case _ => die
}
val client = HttpClients.createDefault()
val uri = new URI(s"http://${Settings.Host}:${Settings.Port}/api/v1/user/$emailAddress")
val post = new HttpPost(uri)
post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
post.addHeader(HttpHeaders.AUTHORIZATION, Settings.ApiKey)
println(post.toString)
val req = ProvisionRequest(None, if (certPem.length > 0) Some(Seq(certPem)) else None)
val mapper = new ObjectMapper().registerModule(DefaultScalaModule)
val json = mapper.writeValueAsString(req)
println(json)
post.setEntity(new StringEntity(json))
val resp = client.execute(post)
try {
val entity = resp.getEntity
println(resp.getStatusLine.getStatusCode, resp.getStatusLine.getReasonPhrase)
println(IOUtils.toString(entity.getContent, StandardCharsets.UTF_8))
} finally {
resp.close()
}
}
}
示例4: AlfrescoFileUploader
//设置package包名称以及导入依赖的类
package pl.com.bms.fileSynchronizer.fileUploader.alfresco
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.utils.URIBuilder
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.impl.client.HttpClients
import pl.com.bms.fileSynchronizer.config.Configuration
import pl.com.bms.fileSynchronizer.fileUploader.{FileUploader, UploadResult}
class AlfrescoFileUploader(val configuration: Configuration) extends FileUploader {
val baseUrl = configuration.connection.url + "/alfresco/service/api/upload"
val token = Authentication.getToken(configuration.connection.url, configuration.connection.login, configuration.connection.password)
override def uploadFile(path: String): UploadResult = {
val sourceFile = configuration.sourceRoot + path
val uploadFilePart = new FileBody(new java.io.File(sourceFile))
val reqEntity = MultipartEntityBuilder.create()
.addPart("filedata", uploadFilePart)
.addTextBody("destination", configuration.destinationRoot)
.addTextBody("path", path)
.build()
val url = new URIBuilder(baseUrl)
.addParameter("alf_ticket", token)
.build()
val httpPost = new HttpPost(url)
httpPost.setEntity(reqEntity)
val response = HttpClients.createDefault().execute(httpPost)
UploadResult(response.getStatusLine.getStatusCode.toString, Some(response.getStatusLine.getReasonPhrase))
}
}
示例5: Client
//设置package包名称以及导入依赖的类
package com.stulsoft.mailgun4s
import org.apache.http.auth.{AuthScope, UsernamePasswordCredentials}
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.{CloseableHttpResponse, HttpPost}
import org.apache.http.impl.client.{BasicCredentialsProvider, HttpClients}
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
import org.apache.http.{HttpStatus, NameValuePair}
class Client {
private lazy val conf = new Config
def sendMail(mail: Mail): Unit = {
val url = conf.urlToSendMessage.format(conf.apiVersion, conf.domain)
val post = new HttpPost(url)
val credentials = new UsernamePasswordCredentials("api", conf.apiKey)
val credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(new AuthScope("api.mailgun.net", 443), credentials)
val httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()
val params = new java.util.ArrayList[NameValuePair]()
params.add(new BasicNameValuePair("from", mail.from))
params.add(new BasicNameValuePair("to", mail.to))
mail.cc.foreach(cc => params.add(new BasicNameValuePair("cc", cc)))
params.add(new BasicNameValuePair("subject", mail.subject))
params.add(new BasicNameValuePair(mail.body.bodyType, mail.body.bodyContent))
post.setEntity(new UrlEncodedFormEntity(params))
var response: CloseableHttpResponse = null
try {
response = httpClient.execute(post)
println(s"response.setStatusCode: ${response.getStatusLine}")
if (response.getStatusLine.getStatusCode == HttpStatus.SC_OK) {
val entity = response.getEntity
println(s"Response: ${EntityUtils.toString(entity)}")
EntityUtils.consume(entity)
}
}
catch {
case e: Exception => println(e.getMessage)
}
finally {
if (response != null)
response.close()
}
}
}
object tt extends App {
val m = Mail("[email protected]", "[email protected]", None, "test 3", HtmlBody("<htm><h1>Header</h1>text</html>"))
new Client sendMail m
}
示例6: initHttpClient
//设置package包名称以及导入依赖的类
package freedomandy.client
import org.apache.http.Header
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ByteArrayEntity
import org.apache.http.impl.client.{BasicResponseHandler, CloseableHttpClient, HttpClients}
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.slf4j.LoggerFactory
trait HttpClient {
val logg =LoggerFactory.getLogger(this.getClass)
val client: CloseableHttpClient = initHttpClient()
var connMgr: PoolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager()
def initHttpClient(): CloseableHttpClient = {
val config = RequestConfig.custom().build()
val client: CloseableHttpClient = HttpClients.custom()
.setConnectionManager(connMgr)
.setDefaultRequestConfig(config).build()
return client
}
def close(): Unit = {
connMgr.close()
}
def handlePostRequest(url: String, headers: List[Header], jsonBody: String): String = {
val post = new HttpPost(url)
headers.foreach { post.addHeader(_) }
val entity = new ByteArrayEntity(jsonBody.getBytes("UTF-8"))
post.setEntity(entity)
val result = client.execute(post, new BasicResponseHandler())
return result
}
}
示例7: post
//设置package包名称以及导入依赖的类
package main.java.eyepatch.input_sources
import java.util
import main.java.eyepatch.{Channel, OutputManager}
import org.apache.http.NameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.message.BasicNameValuePair
trait Networked {
val HOST = "http://localhost:5000"
def post(operation : String, parameters : Map[String, String]) : String = {
val post = new HttpPost(HOST + "/" + operation)
var nameValuePairs = new util.ArrayList[NameValuePair]()
parameters.foreach { case (key, value) =>
nameValuePairs.add(new BasicNameValuePair(key, value))
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairs))
post.setHeader("Content-type", "application/x-www-form-urlencoded")
val post_response = (new DefaultHttpClient).execute(post)
OutputManager.print(Channel.Debug, "Networked Bot: " + post_response)
return post_response.getEntity.getContent.toString
}
def get(operation : String, parameters : Map[String, String]) : String = {
val query_string = "?" + parameters.map{ case (key, value) => key + "=" + value}.mkString("&")
val get_request = new HttpGet(HOST + "/" + operation + query_string)
get_request.addHeader("Content-type", "application/x-www-form-urlencoded")
val get_response = (new DefaultHttpClient).execute(get_request)
OutputManager.print(Channel.Debug, "Networked Bot: " + get_response)
val inputStream = get_response.getEntity.getContent
val content = io.Source.fromInputStream(inputStream).getLines.mkString
inputStream.close
return content
}
}
示例8: ReCaptchaImpl
//设置package包名称以及导入依赖的类
package webby.form.field.recaptcha
import java.io.IOException
import java.util
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.apache.http.NameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.HttpPost
import org.apache.http.message.BasicNameValuePair
import webby.api.mvc.RequestHeader
import webby.commons.io.StdJs
import scala.annotation.tailrec
import scala.util.Random
class ReCaptchaImpl(val config: ReCaptchaConfig) extends ReCaptcha {
protected val httpClient = config.initHttpClient
@tailrec
private def readUrl[A](fn: => A, remainingTries: Int = 15): A = {
try {
fn
} catch {
case e: IOException =>
if (remainingTries <= 1) throw new RuntimeException("Cannot receive captcha response for 15 tries", e)
Thread.sleep(Random.nextInt(500))
readUrl(fn, remainingTries - 1)
}
}
override def solve(reCaptchaResponse: String)(implicit req: RequestHeader): Boolean = {
if (reCaptchaResponse.isEmpty) false
else {
val verifyResult: ReCaptchaVerify =
readUrl({
val post: HttpPost = new HttpPost("https://www.google.com/recaptcha/api/siteverify")
post.setEntity(
new UrlEncodedFormEntity(util.Arrays.asList[NameValuePair](
new BasicNameValuePair("secret", config.secretKey),
new BasicNameValuePair("response", reCaptchaResponse),
new BasicNameValuePair("remoteip", req.remoteAddress))))
val response = httpClient.execute(post)
StdJs.get.mapper.readValue(response.getEntity.getContent, classOf[ReCaptchaVerify])
})
verifyResult.success
}
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
case class ReCaptchaVerify(success: Boolean)