首页 > 代码库 > 通过GET方法返回定义的任意对象

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

package util;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.time.Duration;import java.time.Instant;import java.time.ZoneOffset;import java.time.ZonedDateTime;import java.util.List;import java.util.stream.Collectors;import java.util.stream.IntStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.MapperFeature;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;public class HttpClientUtil {	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;	}}

  

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