一、传输form表单数据
public static HttpResponseBean sendForm(String url , Map<String,String> data, Map<String,String> heards){
try {
List<NameValuePair> pair = new ArrayList<>();
if (data != null ){
Set<Entry<String, String>> entries = data.entrySet();
for (Entry<String, String> entry : entries) {
pair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
HttpClient client = HttpClients.createDefault();
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair,"UTF-8");
HttpPost post = new HttpPost(url);
post.setEntity(entity);
if (heards !=null ){
Set<Entry<String, String>> entries = heards.entrySet();
for (Entry<String, String> entry : entries) {
post.setHeader(entry.getKey(),entry.getValue());
}
}
post.setConfig(RequestConfig.custom().setConnectTimeout(50000)
.setConnectionRequestTimeout(50000).setSocketTimeout(50000)
.setRedirectsEnabled(true).build());
HttpResponse result = client.execute(post);
if (result != null){
HttpResponseBean bean = new HttpResponseBean();
bean.setStatusCode(result.getStatusLine().getStatusCode());
String content = EntityUtils.toString(result.getEntity(), "UTF-8");
bean.setContent(content);
return bean;
}
} catch (Exception e) {
logger.error("HttpUtil method:sendForm fail :" ,e);
}
return null;
}
使用方法:
//设置表单参数
HashMap<String, String> data = new HashMap<>();
data.put("code",code);
data.put("client_id",Servers.CS_PORTAL_KEYCLOAK_CLIENT_ID);
data.put("redirect_uri",keyCloakRedirectUrl);
data.put("grant_type",Servers.CS_PORTAL_KEYCLOAK_GRANT_TYPE);
//设置请求头
HashMap<String, String> heards = new HashMap<>();
heards.put("Content-Type","application/x-www-form-urlencoded");
HttpResponseBean res = HttpsUtil.sendForm(Servers.CS_PORTAL_KEYCLOAK_TOKEN_URL,data,heards);
//响应成功后,处理数据
if (res.getStatusCode()==200){}
二、发送get post put 请求
public class HttpsUtil {
private static final Logger logger = PdLogger.getLogger();
private HttpsUtil() {
}
public static HttpResponseBean doPost(String url, String data, Map<String,String> headers) throws HttpConnectException {
return send(url, data, headers, "POST", 30000);
}
public static HttpResponseBean doPost(String url, String data, Map<String,String> headers, int timeout) throws HttpConnectException {
return send(url, data, headers, "POST", timeout);
}
public static HttpResponseBean doPut(String url, String data, Map<String,String> headers) throws HttpConnectException {
return send(url, data, headers, "PUT", 30000);
}
public static HttpResponseBean doPut(String url, String data, Map<String,String> headers, int timeout) throws HttpConnectException {
return send(url, data, headers, "PUT", timeout);
}
public static HttpResponseBean doGet(String url, Map<String,String> headers) throws HttpConnectException {
return send(url, null, headers, "GET", 30000);
}
public static HttpResponseBean doGet(String url, Map<String,String> headers, int timeout) throws HttpConnectException {
return send(url, null, headers, "GET", timeout);
}
public static HttpResponseBean send(String url, String data, Map<String,String> headers, String method, int timeout) throws HttpConnectException {
StringBuilder response = null;
OutputStreamWriter out = null;
BufferedReader in = null;
HttpsURLConnection httpsCon = null;
Integer responseCode = null;
try {
url = url.replaceAll(" ","%20");
//Proxy proxy = null;
Proxy proxy = Proxy.NO_PROXY;
logger.debug("Proxy IP: " + Servers.PROXY_IP);
if (Servers.PROXY_IP != null && !"".equals(Servers.PROXY_IP)) {
logger.debug("Create proxy.");
InetSocketAddress proxyInet = new InetSocketAddress(Servers.PROXY_IP, Servers.PROXY_PORT);
proxy = new Proxy(Proxy.Type.HTTP, proxyInet);
}
logger.debug("proxy: " + proxy.toString());
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAllX509TrustManager() }, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new TrustHostnameVerifier());
URL httpsUrl = new URL(url);
if (proxy == Proxy.NO_PROXY) {
logger.debug("proxy = NO_PROXY");
httpsCon = (HttpsURLConnection) httpsUrl.openConnection();
} else {
logger.debug("proxy != NO_PROXY");
httpsCon = (HttpsURLConnection) httpsUrl.openConnection(proxy);
}
httpsCon.setRequestMethod(method);
httpsCon.setDoInput(true);
httpsCon.setDoOutput(true);
httpsCon.setUseCaches(false);
httpsCon.setConnectTimeout(timeout);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpsCon.setRequestProperty(entry.getKey(), entry.getValue());
}
}
if (data != null && data.length() > 0) {
out = new OutputStreamWriter(httpsCon.getOutputStream(), "UTF-8");
out.write(data);
out.flush();
}
InputStream responseStream = null;
try
{
responseCode = httpsCon.getResponseCode();
responseStream = httpsCon.getInputStream();
}
catch(IOException e)
{
responseCode = httpsCon.getResponseCode();
responseStream = httpsCon.getErrorStream();
}
logger.info("HttpUtil response code: " + responseCode + ", url: " + url);
in = new BufferedReader(new InputStreamReader(responseStream, "UTF-8"));
String inputLine = null;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
String content = response != null && response.length() > 0 ? response.toString() : null;
HttpResponseBean bean = new HttpResponseBean();
bean.setStatusCode(responseCode);
bean.setContent(content);
return bean;
} catch (Exception e) {
logger.error("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode, e);
throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode, e);
} finally {
try {
if (out != null)
out.close();
} catch (Exception e) {
throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode,
e);
}
try {
if (in != null)
in.close();
} catch (Exception e) {
throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode,
e);
}
}
}