java代码RestTemplate的简单使用

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Auther ztf
 * @Date 2019/1/3 9:19
 * @Description 首先获取token ,进行http请求
 */
public class FaceHttpUtils {


    public static String getToken()
    {
        String url = "https://baidu.com";
        RestTemplate template = new RestTemplate();
        String param ="{\n" +
                "\"organisation\": \"lo\",\n" +
                "\"username\": \"lo\",\n" +
                "\"password\": \"123456\"\n" +
                "}";
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/json");
        HttpEntity httpEntity = new HttpEntity<>(param,requestHeaders);
        ResponseEntity response = template.exchange(url,HttpMethod.POST,httpEntity, ServerResponse.class,param);
        JSONObject object=JSONObject.parseObject(JsonUtils.objectToJson(response.getBody().getData()));
        return  object.getString("token");
    }


    public static String getHttp(String url,String token,Map paramMap)
    {

        RestTemplate template = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", "application/json");
        requestHeaders.add("X-Token", token);
        HttpEntity> httpEntity = new HttpEntity<>(null,requestHeaders);
        ResponseEntity response = template.exchange(url, HttpMethod.GET, httpEntity, ServerResponse.class,paramMap);
        return JsonUtils.objectToJson(response.getBody().getData());
    }

}

 

调用方式:

String token=FaceHttp.getToken();
String url = "https://baidu.com?withShopInfo={withShopInfo}"; //get 参数必加
Map paramMap = new HashMap<>();
paramMap.put("withShopInfo",true);
String str= FaceHttpUtils .getHttp(url,token,paramMap);
List faceShops = JsonUtils.jsonToList(str, FaceShops.class);//JsonUtils为JSON解析类

 

你可能感兴趣的:(Java开发的工具类utils)