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

Posted 兰猫那一家子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过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方法返回定义的任意对象的主要内容,如果未能解决你的问题,请参考以下文章

10方法的定义和重载和递归

描述器

解析云代码 request.object.get(key) 总是返回 undefined

9.13面经

JAVA方法的定义

java 如何实现判断一个对象所有的属性是不是为空