首页 > 代码库 > 通过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方法返回定义的任意对象
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。