springweb里面的post和get请求

  • 主类RestTemplate

   

  • 代码
    public xxx getinfo(String requestUrl, Map<String,Object> requestParameter){
    		/**  主方法  */
    		RestTemplate restTemplate = new RestTemplate();
    		/**  请求头  */
    		HttpHeaders headers = new HttpHeaders();
    		/**  请求方式  */
    		HttpMethod method = HttpMethod.POST;
    		/**  设置格式  */
    		headers.setContentType(MediaType.APPLICATION_JSON);
    		/**  参数格式化  */
    		HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParameter, headers);
    		/**  请求  */
    		ResponseEntity<String> response = restTemplate.exchange(requestUrl, method, requestEntity, String.class);
    		/**  数据打印  */
    		String data = response.getBody();
    
    		/**   对应自己的实体类 */
    		return gson.fromJson(data, xxx.class);
    	}
    

      工具类

  • public class GsonUtil {
    	private static Gson gson;
    
    	private GsonUtil() {
    	}
    
    	public static Gson getInstance() {
    		if (gson == null) {
    			gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
    		}
    
    		return gson;
    	}
    
    }
    

      

    public class GsonUTCDateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
    
    	private final DateFormat dateFormat;
    
    	public GsonUTCDateAdapter() {
    		dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.CHINA);
    		dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    	}
    
    	@Override
    	public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext context) {
    		return new JsonPrimitive(dateFormat.format(date));
    	}
    
    	@Override
    	public synchronized Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) {
    		try {
    			return dateFormat.parse(jsonElement.getAsString());
    		} catch (ParseException e) {
    			throw new JsonParseException(e);
    		}
    	}
    
    }
    

      

原文地址:https://www.cnblogs.com/wsycoo/p/15766888.html