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.client.methods.CloseableHttpResponse; 027import org.apache.http.client.methods.HttpGet; 028import org.apache.http.client.methods.HttpPost; 029import org.apache.http.entity.ContentType; 030import org.apache.http.entity.StringEntity; 031import org.apache.http.impl.client.CloseableHttpClient; 032import org.apache.http.impl.client.HttpClients; 033import org.apache.http.util.EntityUtils; 034 035/** 036 * Http client that handle GET request with a body. 037 * 038 * @since 7.3 039 */ 040public class HttpClient { 041 private final static String UTF8_CHARSET = "UTF-8"; 042 043 private static class HttpGetWithEntity extends HttpPost { 044 public final static String METHOD_NAME = "GET"; 045 046 public HttpGetWithEntity(String url) { 047 super(url); 048 } 049 050 @Override 051 public String getMethod() { 052 return METHOD_NAME; 053 } 054 } 055 056 public static String get(String url) throws IOException { 057 CloseableHttpClient client = HttpClients.createDefault(); 058 HttpGet httpget = new HttpGet(url); 059 try (CloseableHttpResponse response = client.execute(httpget)) { 060 HttpEntity entity = response.getEntity(); 061 return entity != null ? EntityUtils.toString(entity) : null; 062 } 063 } 064 065 public static String get(String url, String payload) throws IOException { 066 if (payload == null) { 067 return get(url); 068 } 069 CloseableHttpClient client = HttpClients.createDefault(); 070 HttpGetWithEntity e = new HttpGetWithEntity(url); 071 StringEntity myEntity = new StringEntity(payload, ContentType.create(MediaType.APPLICATION_FORM_URLENCODED, 072 UTF8_CHARSET)); 073 e.setEntity(myEntity); 074 try (CloseableHttpResponse response = client.execute(e)) { 075 HttpEntity entity = response.getEntity(); 076 return entity != null ? EntityUtils.toString(entity) : null; 077 } 078 } 079}