public static <T> T getByUrl(String requestUrl, Class<T> 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

 posted on 2017-01-05 00:21  兰猫-兰兰  阅读(988)  评论(0编辑  收藏  举报