前言

由于之前一直想用前端调用mojang官网的api来获取皮肤,无奈遇到了跨域问题,只好放弃,由于之前一直使用原生javaweb,就放弃了,但是网站已经升级到了springboot,发送http请求已经是很简单的事情了,就将方法记录下来了,希望下面的方法也可以帮助到你。

get请求

package com.wehao.myweb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
@ResponseBody
public class GetMcUidController {
    @Autowired
    RestTemplate restTemplate; //此处可能会爆红,下面会提供解决方法

    @GetMapping("/xxx") //访问地址
    public Map<String,Object> getuuid() {
        String url = "https://api.mojang.com/users/profiles/minecraft/name"; //请求地址
        Map<String,Object> uuid = restTemplate.getForObject(url,Map.class);
        return uuid;
    }
}

问题解决

RestTemplate restTemplate; 爆红解决方案
这是因为在springboot1.4以及以后的版本中,需要手动创建一个RestTemplate的配置.

package com.wehao.myweb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}