import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* HTTP请求/响应数据处理工具
* @author 周正德(CN) Bond(EN)
*
*/
public class HttpUtils {
/**
* 设置头
*/
public static final String CHARACTER_ENCODING = “UTF-8”;
public static final String METHOD_POST = “POST”;
public static final String CONTENT_TYPE = “Content_Type”;
/**
* 响应流写入
*
* @param response
* @param data
* @throws IOException
*/
public static void responseWrite(HttpServletResponse response, byte[] data) throws IOException {
if (data != null) {
response.setContentLength(data.length);
DataOutputStream out = new DataOutputStream(response.getOutputStream());
out.write(data);
out.flush();
out.close();
}
}
/**
* 读取请求流
*
* @param request
* @return
* @throws IOException
*/
public static byte[] requestRead(HttpServletRequest request) throws IOException {
int contentLength = request.getContentLength();
byte[] data = null;
if (contentLength > 0) {
data = new byte[contentLength];
InputStream is = request.getInputStream();
DataInputStream dis = new DataInputStream(is);
dis.readFully(data);
dis.close();
}
return data;
}
/**
* 以POST方法接受请求数据 一般使用这个即可
* @param url
* @param requestData
* @return
* @throws Exception
*/
public static byte[] postRequest(String url, byte[] requestData) throws Exception {
Properties properties = new Properties();
properties.setProperty(CONTENT_TYPE, “application/octet-stream;charset=” + CHARACTER_ENCODING);
return postRequest(url, requestData, properties);
}
/**
* 以POST方法接受请求数据
* @param urlString
* @param requestData
* @param properties
* @return
* @throws Exception
*/
public static byte[] postRequest(String urlString, byte[] requestData, Properties properties) throws Exception {
byte[] responseData = null;
HttpsURLConnection con = null;
try {
URL url = new URL(urlString);
con = (HttpsURLConnection) url.openConnection();
if ((properties != null) && (properties.size() > 0)) {
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue());
con.setRequestProperty(key, value);
}
}
con.setRequestMethod(METHOD_POST);
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
if (requestData != null) {
dos.write(requestData);
}
dos.flush();
dos.close();
DataInputStream dis = new DataInputStream(con.getInputStream());
int length = con.getContentLength();
if (length > 0) {
responseData = new byte[length];
dis.readFully(responseData);
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
return responseData;
}
}