java Common platform interface utility class HttpConnectUtil instance code
- 2020-12-10 00:44:56
- OfStack
Examples are as follows:
package com.common.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.common.weixin.access.util.MyX509TrustManager;
/**
* Common interface utility class for public platforms
*
* @author
* @date 2013-08-09
*/
public class HttpConnectUtil {
private static Logger log = LoggerFactory.getLogger(HttpConnectUtil.class);
/**
* initiate https Request and get the result
*
* @param requestUrl Request the address
* @param requestMethod Request mode ( GET , POST )
* @param outputStr Submitted data
* @return JSONObject( through JSONObject.get(key) Means of acquisition json The attribute value of the )
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
String result = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
// Sets the generic request properties
httpUrlConn.setRequestProperty("accept", "*/*");
httpUrlConn.setRequestProperty("connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "utf-8");
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// Set the request mode ( GET/POST )
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// When there is data to commit
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// Pay attention to the coding format, prevent Chinese random code
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// Converts the returned input stream into a string
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// Release resources
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
result = buffer.toString();
//jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return result;
}
/**
* initiate https Request and get the result
*
* @param requestUrl Request the address
* @param requestMethod Request mode ( GET , POST )
* @param outputStr Submitted data
* @return Result string
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception{
String result = null;
StringBuffer buffer = new StringBuffer();
try {
// create SSLContext Object and initialize it with the trust manager we specified
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// From the above SSLContext Get from the object SSLSocketFactory object
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
// Sets the generic request properties
httpUrlConn.setRequestProperty("accept", "*/*");
httpUrlConn.setRequestProperty("connection", "Keep-Alive");
httpUrlConn.setRequestProperty("Charset", "utf-8");
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// Set the request mode ( GET/POST )
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// When there is data to commit
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// Pay attention to the coding format, prevent Chinese random code
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// Converts the returned input stream into a string
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// Release resources
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
result = buffer.toString();
//jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error(requestUrl + " server connection timed out.");
throw new Exception(" Connection server timeout ");
} catch (Exception e) {
log.error(requestUrl +" https request error:{}", e);
throw new Exception("HTTPS Request error ");
}
return result;
}
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}