001package org.nuxeo.elasticsearch.http.readonly;/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Benoit Delbosc
016 */
017
018import java.io.IOException;
019
020import javax.ws.rs.core.MediaType;
021
022import org.apache.http.HttpEntity;
023import org.apache.http.client.methods.CloseableHttpResponse;
024import org.apache.http.client.methods.HttpGet;
025import org.apache.http.client.methods.HttpPost;
026import org.apache.http.entity.ContentType;
027import org.apache.http.entity.StringEntity;
028import org.apache.http.impl.client.CloseableHttpClient;
029import org.apache.http.impl.client.HttpClients;
030import org.apache.http.util.EntityUtils;
031
032/**
033 * Http client that handle GET request with a body.
034 *
035 * @since 7.3
036 */
037public class HttpClient {
038    private final static String UTF8_CHARSET = "UTF-8";
039
040    private static class HttpGetWithEntity extends HttpPost {
041        public final static String METHOD_NAME = "GET";
042
043        public HttpGetWithEntity(String url) {
044            super(url);
045        }
046
047        @Override
048        public String getMethod() {
049            return METHOD_NAME;
050        }
051    }
052
053    public static String get(String url) throws IOException {
054        CloseableHttpClient client = HttpClients.createDefault();
055        HttpGet httpget = new HttpGet(url);
056        try (CloseableHttpResponse response = client.execute(httpget)) {
057            HttpEntity entity = response.getEntity();
058            return entity != null ? EntityUtils.toString(entity) : null;
059        }
060    }
061
062    public static String get(String url, String payload) throws IOException {
063        if (payload == null) {
064            return get(url);
065        }
066        CloseableHttpClient client = HttpClients.createDefault();
067        HttpGetWithEntity e = new HttpGetWithEntity(url);
068        StringEntity myEntity = new StringEntity(payload, ContentType.create(MediaType.APPLICATION_FORM_URLENCODED,
069                UTF8_CHARSET));
070        e.setEntity(myEntity);
071        try (CloseableHttpResponse response = client.execute(e)) {
072            HttpEntity entity = response.getEntity();
073            return entity != null ? EntityUtils.toString(entity) : null;
074        }
075    }
076}