java带token的Http请求

//请求url伪代码

List  message = null;

HttpHeaders headers = creatHttpHeaders(); //封装header方法

restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("utf-8")));

HttpEntity requestEntity = new HttpEntity(msgQuery,headers);//msgQuery里面封装了请求参数,和对方约定好保持一致

ResponseEntity  exchange = restTemplate.exchange(url,HttpMethod.Post,requestEntity,String.class);

String status = exchange.getStatusCode().toString();

if("200 OK".equals(status)){

  Map mapData = JSON.parseObject(exchange.getBody(),Map.class);

  if(null != mapData.get("data")){

     Map mapList = JSON.parseObjec(mapData.get("data").toString,Map.class);

    String listStr = mapList.get("list").toString;

   message= JSON.parseArray(listStr,Message.class);

   }

}

//封装header方法

private HttpHeaders createHttpHeaders(){

  HttpHeaders headers = new HttpHeaders();

  //自定义报文头

  headers.setContentType(new MediaType("application","json",Charset.forName("utf-8")));

  //设置接收

  header.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));

  headers.setAcceptCharset(Lists.newArrayList(Charset.forName("utf-8")));

  //拿token

  String token = getToken();

  headers.add("token",token);

  return headers;

}

//得到token

private String getToken(){

HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

//从header中取

String value = request.getHeader("token");

if(StringUtils.isEmpty(value)){

  //从cookie中取

  Cookie[] cookies = request.getCookies();

  if(ArrayUtils.isNotEmpty(cookies)){

  for(Cookie cookie :cokies){

   if("token".equalsIgnoreCase(cookie.getName())){

    value = cookie.getValue();

   break;

  }

 }

 }

//cookie中也没取到,则在param里面取

if(StringUtils.isEmpty(value)){

  value = request.getParameter("token");

}

}

return value;

}

 

你可能感兴趣的:(java)