spring boot使用自带的RestTemplate调用接口
2017-05-11 本文已影响0人
彩虹之梦
以用户接口为例
@Service
class UserService {
@Value("\${tiangu.user.url}")
lateinit private var userServiceUrl: String
@Autowired
lateinit private var utils: ApiUtils
@Autowired
lateinit private var mongoTemplate: MongoTemplate
// 注册
fun register(appId: String, params: Map<String, String>): Any {
val request = RequestEntity(params, buildHeader(appId), HttpMethod.POST, URI("$userServiceUrl/user/register"))
val user = utils.restTemplate.exchange(request, User::class.java).body
mongoTemplate.insert(user)
return mapOf(
"accessToken" to user.token,
"accessExpire" to user.expire
)
}
// 登录
fun login(appId: String, params: Map<String, String>): Any {
val request = RequestEntity(params, buildHeader(appId), HttpMethod.POST, URI("$userServiceUrl/user/login"))
val user = utils.restTemplate.exchange(request, User::class.java).body
val tempUser = mongoTemplate.findOne(Query(Criteria("userUUID").`is`(user.userUUID)), User::class.java)
if (tempUser != null) {
tempUser.token = user.token
tempUser.expire = user.expire
mongoTemplate.save(tempUser)
} else {
mongoTemplate.insert(user)
}
return mapOf(
"accessToken" to user.token,
"accessExpire" to user.expire
)
}
// 修改密码
fun modify(appId: String, params: Map<String, String>) {
val mobile = params["mobile"] ?: throw ApiException("0", "用户手机号不能为空")
val code = params["code"] ?: throw ApiException("0", "验证码不能为空")
val password = params["password"] ?: throw ApiException("0", "新密码不能为空")
// 校验验证码
smsService.verifyCode(mobile, appId, code)
val request = RequestEntity(mapOf(
"mobile" to mobile,
"password" to password
), buildHeader(appId), HttpMethod.POST, URI("$userServiceUrl/user/modify"))
utils.restTemplate.exchange(request, String::class.java).body
}
// 获取用户信息
fun info(user: User, appId: String): Any {
val request = RequestEntity(null, buildHeader(appId, mapOf("X-USER-TOKEN" to user.token!!)), HttpMethod.GET, URI("$userServiceUrl/user/info"))
return utils.restTemplate.exchange(request, Map::class.java).body
}
// 获取联系人列表
fun getContacts(appId: String, token: String): List<Passenger> {
val request = RequestEntity<Any>(null, buildHeader(appId, mapOf("X-USER-TOKEN" to token)), HttpMethod.GET, URI("$userServiceUrl/contacts"))
val type = utils.objectMapper.typeFactory.constructCollectionType(List::class.java, Passenger::class.java)
val body = utils.restTemplate.exchange(request, String::class.java).body
return utils.objectMapper.readValue(body, type)
}
// 添加、修改联系人
fun addContact(appId: String, passenger: Passenger, token: String): Passenger {
passenger.name ?: throw ApiException("0", "请求参数不正确")
passenger.mobile ?: throw ApiException("0", "请求参数不正确")
passenger.cardType ?: throw ApiException("0", "请求参数不正确")
passenger.cardNo ?: throw ApiException("0", "请求参数不正确")
val request = RequestEntity<Any>(passenger, buildHeader(appId, mapOf("X-USER-TOKEN" to token)), HttpMethod.POST, URI("$userServiceUrl/contacts"))
return utils.restTemplate.exchange(request, Passenger::class.java).body
}
// 删除联系人
fun deleteContact(appId: String, token: String, uuid: String) {
val request = RequestEntity<Any>(null, buildHeader(appId, mapOf("X-USER-TOKEN" to token)), HttpMethod.DELETE, URI("$userServiceUrl/contacts/$uuid"))
utils.restTemplate.exchange(request, Passenger::class.java).body
}
fun bind(appId: String, platform: String, platformId: String): User {
val curUser = mongoTemplate.findOne(Query.query(Criteria("platform").`is`(platform).and("openId").`is`(platformId)), User::class.java)
if (curUser != null && curUser.expire!!.time > System.currentTimeMillis()) return curUser
val request = RequestEntity(mapOf(
"uuid" to platformId,
"type" to platform
), buildHeader(appId), HttpMethod.POST, URI("$userServiceUrl/user/bind"))
val user = utils.restTemplate.exchange(request, User::class.java).body
user.platform = platform
user.openId = platformId
val tempUser = mongoTemplate.findOne(Query(Criteria("userUUID").`is`(user.userUUID)), User::class.java)
if (tempUser == null) {
mongoTemplate.insert(user)
return user
} else {
BeanUtils.copyProperties(user, tempUser)
mongoTemplate.save(tempUser)
return tempUser
}
}
// 获取用户信息
fun getUser(token: String) = mongoTemplate.findOne(Query.query(Criteria("token").`is`(token).and("expire").gt(Date())), User::class.java) ?: throw ApiException("401", "需要权限")
fun findBy(key: String, value: Any) = mongoTemplate.findOne(Query.query(Criteria(key).`is`(value)), User::class.java)
// 上传头像
fun uploadHead(appId: String, user: User, uploadBytes: ByteArray): Any {
// 上传到七牛云
val uploadManager = UploadManager(Configuration(Zone.zone0()))
val auth = create(accessKey, secretKey)
val upToken = auth.uploadToken(bucket)
try {
val response = uploadManager.put(uploadBytes, null, upToken)
//解析上传成功的结果
val putRet = Gson().fromJson(response.bodyString(), DefaultPutRet::class.java)
val resUrl = "http://avatars.res.untrip.net/${putRet.hash}"
val request = RequestEntity(mapOf(
"head" to resUrl
), buildHeader(appId, mapOf("X-USER-TOKEN" to user.token!!)), HttpMethod.POST, URI("$userServiceUrl/user/upload"))
utils.restTemplate.exchange(request, Map::class.java).body
return mapOf(
"head" to resUrl
)
} catch (ex: QiniuException) {
throw ApiException("0", "上传图片失败")
}
}
private fun buildHeader(appId: String, params: Map<String, String>? = mapOf()): HttpHeaders {
val httpHeaders = HttpHeaders()
httpHeaders.set("X-APP-ID", appId)
params?.filter { it.key != "X-APP-ID" }?.forEach {
httpHeaders.set(it.key, it.value)
}
return httpHeaders
}
}
utils代码
@Component
open class ApiUtils {
val restTemplate by lazy {
RestTemplateBuilder().additionalMessageConverters(
StringHttpMessageConverter(Charsets.UTF_8),
MappingJackson2HttpMessageConverter()
).build()!!
}
val objectMapper by lazy { ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)!! }
val xmlMapper by lazy { XmlMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)!! }
fun buildUri(url: String, params: Map<String, Any?> = emptyMap()): String {
val query = params.filterValues { it != null }.map { "${it.key}=${it.value}" }.joinToString("&")
val sep = if (url.contains("?")) "&" else "?"
return "$url$sep$query"
}
}