001/* 002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Benoit Delbosc 018 */ 019package org.nuxeo.elasticsearch.http.readonly; 020 021import java.io.IOException; 022 023import javax.ws.rs.core.MediaType; 024 025import org.apache.http.HttpEntity; 026import org.apache.http.HttpHeaders; 027import org.apache.http.client.methods.CloseableHttpResponse; 028import org.apache.http.client.methods.HttpGet; 029import org.apache.http.client.methods.HttpPost; 030import org.apache.http.entity.ContentType; 031import org.apache.http.entity.StringEntity; 032import org.apache.http.impl.client.CloseableHttpClient; 033import org.apache.http.impl.client.HttpClients; 034import org.apache.http.util.EntityUtils; 035 036/** 037 * Http client that handle GET request with a body. 038 * 039 * @since 7.3 040 */ 041public class HttpClient { 042 private static final String UTF8_CHARSET = "UTF-8"; 043 044 private static class HttpGetWithEntity extends HttpPost { 045 public static final String METHOD_NAME = "GET"; 046 047 public HttpGetWithEntity(String url) { 048 super(url); 049 } 050 051 @Override 052 public String getMethod() { 053 return METHOD_NAME; 054 } 055 } 056 057 public static String get(String url) throws IOException { 058 try (CloseableHttpClient client = HttpClients.createDefault()) { 059 HttpGet request = new HttpGet(url); 060 request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); 061 try (CloseableHttpResponse response = client.execute(request)) { 062 HttpEntity entity = response.getEntity(); 063 return entity != null ? EntityUtils.toString(entity) : null; 064 } 065 } 066 } 067 068 public static String get(String url, String payload) throws IOException { 069 if (payload == null) { 070 return get(url); 071 } 072 try (CloseableHttpClient client = HttpClients.createDefault()) { 073 HttpGetWithEntity request = new HttpGetWithEntity(url); 074 request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); 075 request.setEntity( 076 new StringEntity(payload, ContentType.create(MediaType.APPLICATION_FORM_URLENCODED, UTF8_CHARSET))); 077 try (CloseableHttpResponse response = client.execute(request)) { 078 HttpEntity entity = response.getEntity(); 079 return entity != null ? EntityUtils.toString(entity) : null; 080 } 081 } 082 } 083}