package com.kkfun.cocoa.mahjong.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
public class HttpUtil
{
private static Logger log = Logger.getLogger(HttpUtil.class);
private static final String MAC_NAME = "HmacSHA1";
private static final String ENCODING = "UTF-8";
/**
* http请求(get方式)
* @param url
* @param data
* @return
* @throws IOException
*/
public static String requestUrl(String url, HashMap<String, String> data)
throws Exception {
// HttpURLConnection conn = null;
InputStreamReader streamReader = null;
BufferedReader bufferedReader;
StringBuilder sb = null;
String line;
try
{
// if GET....
// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(5000);//连接服务器5s超时
//post请求
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
PrintWriter writer = new PrintWriter(conn.getOutputStream());
// System.out.println(url+"?" +httpBuildQuery(data));
writer.print(httpBuildQuery(data));
writer.flush();
writer.close();
streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
} catch (Exception e) {
// streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");
log.error("requestUrl err", e);
e.printStackTrace();
} finally {
if (streamReader != null) {
bufferedReader = new BufferedReader(streamReader);
sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
}
}
if (sb != null)
{
return sb.toString();
}
return null;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, HashMap<String, String> data) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// URL realUrl = new URL(url);
// // 打开和URL之间的连接
// URLConnection conn = realUrl.openConnection();
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
// 设置通用的请求属性
conn.setConnectTimeout(5000);//连接服务器5s超时
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);//向httpbody输入数据,POST必须
conn.setDoInput(true);//获取输出流,默认true
conn.setRequestMethod("POST");
conn.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = conn.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// log.info(key + "--->" + map.get(key));
// }
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(httpQuery(data));
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
log.error("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String data) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// URL realUrl = new URL(url);
// // 打开和URL之间的连接
// URLConnection conn = realUrl.openConnection();
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
// 设置通用的请求属性
conn.setConnectTimeout(5000);//连接服务器5s超时
// conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);//向httpbody输入数据,POST必须
conn.setDoInput(true);//获取输出流,默认true
conn.setRequestMethod("POST");
conn.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = conn.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// log.info(key + "--->" + map.get(key));
// }
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
// out.print(URLEncoder.encode(data,"UTF-8"));
out.print(data);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
log.error("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, HashMap<String, String> data) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + httpQuery(data);
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
// Map<String, List<String>> map = connection.getHeaderFields();
// // 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("发送GET请求出现异常!",e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* http请求(get方式)
* @param url
* @param data
* @return
* @throws IOException
*/
public static String testrequestUrl(String url, HashMap<String, String> data,int proid)
throws Exception {
// HttpURLConnection conn = null;
InputStreamReader streamReader = null;
BufferedReader bufferedReader;
StringBuilder sb = null;
String line;
try
{
// if GET....
// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty("protocolid",String.valueOf(proid));
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
PrintWriter writer = new PrintWriter(conn.getOutputStream());
// System.out.println(url+"?" +httpBuildQuery(data));
writer.print(httpBuildQuery(data));
writer.flush();
writer.close();
streamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");
} catch (Exception e) {
// streamReader = new InputStreamReader(conn.getErrorStream(), "UTF-8");
log.error("testrequestUrl err", e);
} finally {
if (streamReader != null) {
bufferedReader = new BufferedReader(streamReader);
sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
}
}
if (sb != null)
{
return sb.toString();
}
return null;
}
/**
* postHttp
* @param url
* @param data
* @return 字节流
* @throws Exception
*/
public static InputStream requestUrl2(String url, HashMap<String, String> data) throws Exception
{
try
{
// if GET....
// URL requestUrl = new URL(url + "?" + httpBuildQuery(data));
URL requestUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
PrintWriter writer = new PrintWriter(conn.getOutputStream());
// System.out.println(url+"?" +httpBuildQuery(data));
writer.print(httpBuildQuery(data));
writer.flush();
writer.close();
return conn.getInputStream();
} catch (Exception e)
{
log.error("requestUrl err", e);
} finally
{
}
return null;
}
/**
* 参数编码
* @param data
* @return
*/
public static String httpBuildQuery(HashMap<String, String> data) {
String ret = "";
String k, v;
Iterator<String> iterator = data.keySet().iterator();
while (iterator.hasNext()) {
k = iterator.next();
v = data.get(k);
try {
ret += URLEncoder.encode(k, "utf8") + "=" + URLEncoder.encode(v, "utf8");
} catch (UnsupportedEncodingException e) {
}
ret += "&";
}
return ret.substring(0, ret.length() - 1);
}
/**
* 短信参数编码(短信内容GBK)
* @param data
* @return
*/
public static String httpQuery(HashMap<String, String> data) {
String ret = "";
String k, v;
Iterator<String> iterator = data.keySet().iterator();
while (iterator.hasNext()) {
k = iterator.next();
v = data.get(k);
try {
if (k.equals("msg"))
{
ret += k + "=" + URLEncoder.encode(v, "GBK");
// ret += k + "=" + Utils.changeCharset(k, "GBK");
}else{
ret += k + "=" + v;
}
} catch (UnsupportedEncodingException e) {
}
ret += "&";
}
System.out.println(ret);
log.info("requestinfo=>" + ret);
return ret.substring(0, ret.length() - 1);
}
/**
* 使用 HMAC-SHA1 签名方法对对encryptText进行签名(小米)
*
* @param encryptText 被签名的字符串
* @param encryptKey 密钥
* @return 返回被加密后的字符串
* @throws Exception
*/
public static String hmacSHA1Encrypt(HashMap<String, String> params, String encryptKey)
{
String encryptText = sortString(params);
byte[] data;
try
{
data = encryptKey.getBytes(ENCODING);
// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKey secretKey = new SecretKeySpec(data, MAC_NAME);
// 生成一个指定 Mac 算法 的 Mac 对象
Mac mac = Mac.getInstance(MAC_NAME);
// 用给定密钥初始化 Mac 对象
mac.init(secretKey);
byte[] text = encryptText.getBytes(ENCODING);
// 完成 Mac 操作
byte[] digest = mac.doFinal(text);
StringBuilder sBuilder = bytesToHexString(digest);
return sBuilder.toString();
} catch (Exception e)
{
log.error("hmacSHA1Encrypt err:", e);
}
return null;
}
/**
* 转换成Hex
*
* @param bytesArray
*/
public static StringBuilder bytesToHexString(byte[] bytesArray)
{
if (bytesArray == null)
{
return null;
}
StringBuilder sBuilder = new StringBuilder();
for (byte b : bytesArray)
{
String hv = String.format("%02x", b);
sBuilder.append(hv);
}
return sBuilder;
}
/**
* 将参数按照字母顺序排序
* @param data
* @return
*/
public static String sortString(HashMap<String, String> data){
String[] signArray = {"appId","session","uid"};
StringBuilder sb = new StringBuilder();
for (String key : signArray)
{
String value = data.get(key);
if (value != null && !value.equals("")){
try
{
sb.append(URLEncoder.encode(key, ENCODING))
.append("=")
.append(URLEncoder.encode(value, ENCODING))
.append("&");
}
catch (Exception e)
{
}
}
}
String result = sb.toString();
return result.substring(0, result.length() - 1);
}
/**
* get方式提交短信内容
* @param url
* @return
*/
private static String submit(String url) {
String re = "";
int byteMax = 50;
try {
URL myurl = new URL(url);
URLConnection urlcon = myurl.openConnection();
urlcon.setUseCaches(false);
urlcon.connect();
InputStream inputstream = urlcon.getInputStream();//输出
byte[] buff = new byte[byteMax];
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
int ins;
while ((ins = inputstream.read(buff)) >= 0) {
bytearrayoutputstream.write(buff, 0, ins);
}
re = new String(bytearrayoutputstream.toByteArray());
re.trim();
} catch (MalformedURLException ex) {
log.error("submit SMS MalformedURLException:", ex);
} catch (IOException ex) {
log.error("submit SMS ioexception:", ex);
}
return re;
}
}