1. 实现 httpheader
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.ParseException;
/**
* Demo class
*
* @author Muxin Sun
* @date 2019/10/01
*/
public class HttpHeader implements Header {
private String name;
private String value;
public HttpHeader(String name, String value) {
this.name = name;
this.value = value;
}
@Override
public HeaderElement[] getElements() throws ParseException {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return name;
}
@Override
public String getValue() {
// TODO Auto-generated method stub
return value;
}
}
2. 实现 http 请求封装
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.Header;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import static com.neusoft.rsapm.brain.common.inter.message.Message.SUCCESS_CODE;
/**
* HTTP visit class for http request
*
* @author Muxin Sun
* @date 2019/10/01
*/
public class HttpUtil {
private static final String CHARSET = "utf-8";
private static final String CONTENT_TYPE = "application/json";
public static final String REMOTE_ADDR="remoteAddr";
public static final String REMOTE_PORT="remotePort";
public static String getRemoteAddr(HttpServletRequest request) {
return Objects.nonNull(request.getHeader(REMOTE_ADDR)) ? request.getHeader(REMOTE_ADDR) : request.getRemoteAddr();
}
public static String getRemotePort(HttpServletRequest request) {
return Objects.nonNull(request.getHeader(REMOTE_PORT)) ? request.getHeader(REMOTE_PORT) : String.valueOf(request.getRemotePort());
}
public static CloseableHttpClient getHttpClient() {
return getHttpClient(null);
}
public static CloseableHttpClient getHttpClient(HttpHost proxy) {
CloseableHttpClient client = null;
try {
SSLContext sslcontext = createIgnoreVerifySSL();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext, new DefaultHostnameVerifier())).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CredentialsProvider provider = new BasicCredentialsProvider();
if (proxy!=null) {
client = HttpClients.custom().setConnectionManager(connManager).setProxy(proxy).build();
} else {
client = HttpClients.custom().setConnectionManager(connManager).build();
}
} catch (KeyManagementException | NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return client;
}
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
public static String HttpGET(String url) throws IOException {
return HttpGET(url, new ArrayList<>());
}
public static String HttpGET(String url, List<Header> headers) throws IOException {
return HttpGET(url, headers, null);
}
public static String HttpGET(String url, HttpHost proxy) throws IOException {
return HttpGET(url, new ArrayList<>(), proxy);
}
public static String HttpGET(String url, List<Header> headers, HttpHost proxy) throws IOException {
final CloseableHttpClient client = getHttpClient(proxy);
HttpGet get = new HttpGet(url);
headers.forEach(header -> {
get.addHeader(header.getName(), header.getValue());
});
get.addHeader(HTTP.CONTENT_ENCODING, CHARSET);
get.addHeader(HTTP.CONTENT_TYPE, CONTENT_TYPE);
CloseableHttpResponse resp = client.execute(get);
if (resp.getStatusLine().getStatusCode() != SUCCESS_CODE) {
return null;
}
HttpEntity entity = resp.getEntity();
Scanner sin = new Scanner(EntityUtils.toString(entity));
entity.getContent();
StringBuilder res = new StringBuilder();
while(sin.hasNext()) {
res.append(sin.nextLine());
}
sin.close();
resp.close();
client.close();
return res.toString();
}
public static String HttpPOST(String url, String body) throws IOException {
return HttpPOST(url, body, null);
}
public static String HttpPOST(String url, String body, HttpHost proxy) throws IOException {
return HttpPOST(url, new ArrayList<>(), body, CHARSET, CONTENT_TYPE, proxy);
}
public static String HttpPOST(String url, List<Header> headers, String body) throws IOException {
return HttpPOST(url, headers, body, CHARSET, CONTENT_TYPE, null);
}
public static String HttpPOST(String url, List<Header> headers, String body, HttpHost proxy) throws IOException {
return HttpPOST(url, headers, body, CHARSET, CONTENT_TYPE, proxy);
}
public static String HttpPOST(String url, List<Header> headers, Map<String, Object> params) throws IOException {
return HttpPOST(url, headers, params, null);
}
public static String HttpPOST(String url, List<Header> headers, Map<String, Object> params, HttpHost proxy) throws IOException {
JSONObject body = new JSONObject();
params.forEach(body::put);
return HttpPOST(url, headers, body.toString(), proxy);
}
public static String HttpPOST(String url, List<Header> headers, List<Map<String, Object>> params) throws IOException {
return HttpPOST(url, headers, params, null);
}
public static String HttpPOST(String url, List<Header> headers, List<Map<String, Object>> params, HttpHost proxy) throws IOException {
JSONArray body = new JSONArray();
params.forEach(param -> {
JSONObject jObj = new JSONObject();
param.forEach(jObj::put);
body.add(jObj);
});
return HttpPOST(url, headers, body.toString(), proxy);
}
public static String HttpPOST(String url, List<Header> headers, String body, String charset, String contentType, HttpHost proxy) throws IOException {
final CloseableHttpClient client = getHttpClient(proxy);
HttpPost post = new HttpPost(url);
post.addHeader(HTTP.CONTENT_ENCODING, charset);
post.addHeader(HTTP.CONTENT_TYPE, contentType);
headers.forEach(header -> {
if(!header.getName().toLowerCase().equals(HTTP.CONTENT_LEN.toLowerCase())) {
post.addHeader(header.getName(), header.getValue());
}
});
post.setEntity(new StringEntity(String.valueOf(body), charset));
CloseableHttpResponse resp = client.execute(post);
if (resp.getStatusLine().getStatusCode() != SUCCESS_CODE) {
return null;
}
HttpEntity entity = resp.getEntity();
Scanner sin = new Scanner(EntityUtils.toString(entity));
entity.getContent();
StringBuilder res = new StringBuilder();
while(sin.hasNext()) {
res.append(sin.nextLine());
}
sin.close();
resp.close();
client.close();
return res.toString();
}
}