상세 컨텐츠

본문 제목

HttpClient

스프링

by e7e 2022. 4. 27. 08:17

본문

HttpClient5 라이브러리 추강!

pom.xml

<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>5.2.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5-fluent</artifactId>
    <version>5.2.1</version>
</dependency>

 

@Controller
public class HttpClientTest {

	@GetMapping(value="/google",produces = "application/xml;charset=utf-8")
	@ResponseBody
	public Document getGoogleNews() throws Exception {
		String url = "https://news.google.com/rss/search?q=blackpink&hl=en-US&gl=US&ceid=US:en";
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet getRequest = new HttpGet(url);
		
		CloseableHttpResponse response = httpClient.execute(getRequest);
		//response.setHeader("Content-Type", "application/xml");
		
		Document doc = null;
		DocumentBuilderFactory docBuilder = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = docBuilder.newDocumentBuilder();
		
		doc = builder.parse(response.getEntity().getContent());
		

		return doc;
			
	}

	@GetMapping(value="/google3",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String getGoogleNews3() throws Exception {
		String url = "https://news.google.com/rss/search?q=blackpink&hl=en-US&gl=US&ceid=US:en";
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet getRequest = new HttpGet(url);
		
		CloseableHttpResponse response = httpClient.execute(getRequest);
		//response.setHeader("Content-Type", "application/xml");
		
		XmlMapper xmlMapper = new XmlMapper();
		JsonNode node = xmlMapper.readTree(response.getEntity().getContent());
		

		ObjectMapper jsonMapper = new ObjectMapper();
		
		httpClient.close();
		return jsonMapper.writeValueAsString(node);  
			
	}

	
	
	@GetMapping(value="/google2",produces = "application/json;charset=utf-8")
	@ResponseBody
	public String getGoogleNews2() throws Exception {
		String url = "https://www.flickr.com/services/feeds/photos_public.gne?tags=blackpink&format=json";
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet getRequest = new HttpGet(url);
		
		CloseableHttpResponse response = httpClient.execute(getRequest);
		
		String json = EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8);
				
        httpClient.close();
		return json;
			
	}
}

 

 

'스프링' 카테고리의 다른 글

초간단 WebSocket 채팅  (16) 2022.04.28
MVC이해  (0) 2022.04.27
SQL로그 출력  (0) 2022.04.17
pom.xml등 설정파일 긁어가깅  (0) 2022.04.17
MyBatis(마이바티스) 설정  (0) 2022.04.10

관련글 더보기