码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-01-05 01:42:26      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:ring   ati   try   value   soft   XML   amp   unknown   app   

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方法返回定义的任意对象

标签:ring   ati   try   value   soft   XML   amp   unknown   app   

原文地址:http://www.cnblogs.com/ilazysoft/p/6250784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!