HttpUtil
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.InputStream;
import java.util.Map;
@Slf4j
public class HttpClient {
public HttpClient() {
}
private CloseableHttpClient httpClient = HttpClientBuilder.create().build();
@Autowired
private RequestConfig config;
public String doGet(String url) {
try {
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
CloseableHttpResponse response = this.httpClient.execute(httpGet);
if (response != null) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
public String doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
return this.doGet(uriBuilder.build().toString());
}
public String doPost(String url) throws Exception {
return this.doPost(url, "");
}
public String doPost(String url, String jsonParam) throws Exception {
String result = "";
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Accept-Encoding", "UTF-8");
StringEntity s = new StringEntity(jsonParam, "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
httpPost.setEntity(s);
HttpResponse response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
}
return result;
}
public InputStream getInputStream(String url, String jsonParam) throws Exception {
String result = "";
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(config);
httpPost.setHeader("Content-Type", "application/json");
if (jsonParam.length() > 0) {
httpPost.setEntity(new StringEntity(jsonParam, ContentType.create("application/json", "utf-8")));
HttpResponse response = httpClient.execute(httpPost);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
return entity.getContent();
}
}
return null;
}
}