import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import javax.net.ssl.SSLHandshakeException;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class DistributeUtil
{
private Log log = LogFactory.getLog( DistributeUtil.class);
private DistributeUtil()
{
}
/**
* 单态实例
*/
private static DispenseUtil instance;
/**
* 获得单态实例
*
* @return 单态实例
*/
public static DistributeUtilgetInstance()
{
if (instance == null)
{
instance = new DistributeUtil();
}
return instance;
}
public String httpPost(String httpUrl, String content, String privatekey) throws Exception
{
String resultJson = "";
BufferedReader instream = null;
StringBuffer result = new StringBuffer();
DefaultHttpClient httpClient = new DefaultHttpClient();
// 请求重试处理
HttpRequestRetryHandler myRetryHandler = this.getHttpRequestRetryHandler();httpClient.setHttpRequestRetryHandler(myRetryHandler);
HttpPost httppost = new HttpPost(httpUrl);
// 请求超时
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
// 读取超时
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 12000);
try
{
content = URLEncoder.encode(content, "UTF-8");
byte[] sourceData = content.getBytes();
// 内容参数加密处理
String encryptData = RSAUtil.encryptByPrivateKey(sourceData, privatekey);String signData = RSAUtil.sign(encryptData, privatekey);
StringBuilder josn = new StringBuilder();
josn.append("{\"encryptContent\":\"").append(encryptData).append("\",");
josn.append("\"signContent\":\"").append(signData).append("\"");
josn.append("}");
// 构造最简单的字符串数据
StringEntity entity = new StringEntity(josn.toString(), "application/json", "UTF-8");
httppost.setEntity(entity);
//执行
HttpResponse response = httpClient.execute(httppost);
//获取内容实体
HttpEntity resEntity = response.getEntity();if (resEntity != null)
{
instream = new BufferedReader(
new InputStreamReader(resEntity.getContent(), "UTF-8"));
String temp = null;
temp = instream.readLine();
while (temp != null)
{
result.append(temp);
temp = instream.readLine();
}
}
// 获取返回的字符,验证签名和解密
if (!StringUtil.isEmptyString(result.toString()))
{
JSONObject json = JSONObject.fromObject(result.toString());
String encryptcontent = json.optString("encryptContent").replaceAll(
"\\s*|\t|\r|\n", "");
resultJson = java.net.URLDecoder.decode(new String(RSAUtil.decryptByPrivateKey(
encryptcontent, privatekey)), "UTF-8");
}
}
catch (Exception e)
{
log.error("调用分发接口时出错:" + e);
}
finally
{
if (null != httpClient)
{
httpClient.getConnectionManager().shutdown();
}
if (null != instream)
{
instream.close();
}
}
return resultJson;
}
public String httpGet(String url) throws Exception
{
log.info("----httpGet url = " + url);
HttpRequestRetryHandler myRetryHandler = getHttpRequestRetryHandler();
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setHttpRequestRetryHandler(myRetryHandler);
String responseResult = null;
try
{
// Post请求
HttpGet httpGet = new HttpGet(url);
// 请求超时
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
// 读取超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
// 发送请求
HttpResponse httpresponse = httpclient.execute(httpGet);
// 获取返回数据
HttpEntity entity = httpresponse.getEntity();
responseResult = EntityUtils.toString(entity, "utf-8");
if (entity != null)
{
entity.consumeContent();
}
}
catch (Exception e)
{
log.error("调用接口时出错:" + e);
}
finally
{
if (null != httpclient)
{
httpclient.getConnectionManager().shutdown();
}
}
return responseResult;
}
/**
* 获取HttpRequestRetryHandler
*
* @return
*/
private HttpRequestRetryHandler getHttpRequestRetryHandler()
{
HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler()
{
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context)
{
if (executionCount >= 3)
{
// 超过最大次数则不需要重试
return false;
}
if (exception instanceof NoHttpResponseException)
{
// 服务停掉则重新尝试连接
return true;
}
if (exception instanceof SSLHandshakeException)
{
// SSL异常不需要重试
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent)
{
// 请求内容相同则重试
return true;
}
return false;
}
};
return myRetryHandler;
}
public static void main(String[] args)
{
/* String s = "{\"start\": \"1\",\"end\": \"10\",\"code\": \"10002\",\"orgaid\": \"08315579940B477BB87873DC4384A8FD\","
+ "\"classids\": [\"44B645A8D9224D31AC0479AFA03DBAF5\",\"7408763BF84D4D7AAAAAA3A9B1123FDD\"],"
+ "\"category\": \"2\"}";*/
String s = "{\"start\": \"1\",\"end\": \"10\",\"code\": \"10002\",\"schoolid\": \"9384976415194DDD8FFB9849D1DED2D3\","
+ "\"classid\": \"126E1B0AEEBA4766B712427530950BE6\","
+ "\"category\": \"1\"}";
DistributeUtilre = DistributeUtil.getInstance();
String url = "http://192.168.1.157:58080/aam1/rest/queryClassStudentReq"; // http://192.168.5.104:58080/aamForCP/
String prakey = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAmDQ7j18G+I5ytVnzni4JQZZLU5jZ"
+ "4JuDvTUeVq5LTBS+SHBWGzsQVx4K+W/WpteH8b7R54vmNKrfuXjOgm4zAwIDAQABAkAhDXbBs8k3"
+ "wPd4GoilGSo5bAH/rXnjJOJ+/EISYNdJNgFUarmxyS6GB7hvclrZn9r2MTSVRMQePnrNTsq+t8pB"
+ "AiEA5JIvSCkP7s7prLCX4SStXRhHbpZ6/Q+FXC8TNwtAgwUCIQCqeAQTC5ZU6z12L+YFH0GKb1YY"
+ "zaj9PLMX+neUDoRMZwIgWGimuy2OyRrlTXNcu6vZFooejwrLdXh8Z8SZlQ/YGxUCIDQFrDijsJz5"
+ "rSgENg4aG8ZDc+Ld4FRn0b/fj95/D6DBAiBwl6FYWQOBZmNPaIDIjFD2IXiMLfcyMYFy9gt921WU"
+ "Hg==";
try
{
String str = re.httpPost(url, s, prakey);
System.out.print(str);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}