通过GET方法返回定义的任意对象

	public static  T getByUrl(String requestUrl, Class classOfT) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(MapperFeature.AUTO_DETECT_CREATORS, true);
		objectMapper.configure(
				DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.registerModule(new JavaTimeModule());
		objectMapper
				.configure(
						com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
						false);

		T r = null;
		try {
			HttpGet getRequest = new HttpGet(requestUrl);
			HttpResponse response = httpClient.execute(getRequest);
			HttpEntity entity = response.getEntity();
			String entityStr = EntityUtils.toString(entity, "UTF-8");
			// System.out.println(entityStr);
			r = objectMapper.readValue(entityStr, classOfT);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return r;
	}

  我当时把该方法对应的文件名命名为:HttpClientUtil

你可能感兴趣的:(通过GET方法返回定义的任意对象)