HttpURLConnectionClient
package com.utils; import com.pay.util.AES;
import org.apache.log4j.Logger; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map; /**
* http服务.
*/
public class HttpURLConnectionClient{
private final static String CHARSET = "UTF-8";
private final static int TIMEOUT_COUNT = 3;//超时次数
private static Logger logger = Logger.getLogger(HttpURLConnectionClient.class);
public static SimpleDateFormat sf_yyyy_mm_dd_hh_mm_ss = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static SimpleDateFormat yyyyMMddHHmmssS = new SimpleDateFormat("yyyyMMddHHmmssS");
private static String APP_INTERFACE_SIGN_KEY;
static {
PropertiesUtil properties = new PropertiesUtil("common");
APP_INTERFACE_SIGN_KEY = properties.getValue("APP_INTERFACE_SIGN_KEY");
} public static String requestServer(String url, Map<String, Object> param)
throws Exception
{
String sdate = yyyyMMddHHmmssS.format(new Date());
param.put("reqTime", sdate);
if (url == null)
throw new Exception("Unsupported request type, URL is null");
if (url.startsWith("http://"))
return doPostHttp(url, param);
if (url.startsWith("https://")) {
return doPostHttps(url, param);
}
throw new Exception("Unsupported request type, URL is [ " + url + " ]");
}
/**
* get方式请求
* @param url
* @return
* @throws Exception
*/
public static String doGet(String url,String charset) throws Exception {
URL restServiceURL = new URL(url);
logger.info("####"+sf_yyyy_mm_dd_hh_mm_ss.format(new Date())+"请求OTC接口URL"+url);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setConnectTimeout(5000);
httpConnection.setReadTimeout(8000);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Accept-Charset", charset);
try {
if (httpConnection.getResponseCode() != 200) {
System.out.println("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
} catch (SocketTimeoutException e) {
System.out.println("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage()+",异常信息: " + e.getMessage());
throw new SocketTimeoutException("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
}
BufferedReader responseBuffer = null;
for(int i=0; i< TIMEOUT_COUNT; i++){
try{
responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), "UTF-8"));
break;
} catch (SocketTimeoutException e){
System.out.println("读取响应超时,重新读取,次数: "+ (i+1) +",异常信息: " + e.getMessage());
if(i== TIMEOUT_COUNT -1) {
throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
} catch (Exception e){
System.out.println(e.getMessage());
if(i== TIMEOUT_COUNT -1) {
throw new Exception(e.getMessage());
}
}
}
StringBuffer result= new StringBuffer();
String output = "";
while (null!=(output = responseBuffer.readLine())) {
result.append(output);
}
responseBuffer.close();
httpConnection.disconnect();
if(null==result || "".equals(result)){
throw new Exception();
}
return result.toString();
} /**
* 发送POST http请求
* @param url 路径
* @param param 参数
* @return
* @throws Exception
*/
public static String doPostHttp(String url, Map<String, Object> param) throws Exception {
URL restServiceURL = new URL(url);
StringBuffer params = new StringBuffer();
if(param!=null && param.size()>0) {
Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> element = it.next();
params.append((String)element.getKey()).append("=").append(element.getValue()).append("&");
}
if (params.length() > 0) {
String sign = AES.getInstance().encrypt(params.toString(), APP_INTERFACE_SIGN_KEY);
params.append("Sign=" + sign);
}
}
logger.info(url + "\n\t原始数据---" + param + "\n\t格式化后数据---" + params);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setConnectTimeout(15000);
httpConnection.setReadTimeout(200000);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept-Charset", CHARSET);
//httpConnection.setRequestProperty("Accept", "text/json");
PrintWriter printWriter = null;
for(int i=1;i<=TIMEOUT_COUNT;i++){
try {
printWriter = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), CHARSET));
printWriter.write(params.toString());
break;
}catch(ConnectException e) {
logger.error("连接超时,重新连接,次数: " + (i) + ",异常信息: " + e.getMessage());
if(i==TIMEOUT_COUNT){
throw new ConnectException("连接超时,次数已用完,次数: " + (i) + ",异常信息: " + e.getMessage());
}
}catch(SocketTimeoutException e){
logger.error("请求超时,重新请求,次数: " + (i) + ",异常信息: " + e.getMessage());
if(i==TIMEOUT_COUNT){
throw new SocketTimeoutException("请求超时,次数已用完,请求次数: " + (i) + ",异常信息: " + e.getMessage());
}
} catch(Exception e){
logger.error(e);
if(i==TIMEOUT_COUNT){
throw e;
}
} finally {
if(printWriter!=null) {
printWriter.flush();
printWriter.close();
}
}
}
for(int i=1; i<=TIMEOUT_COUNT; i++) {
try {
if (httpConnection.getResponseCode() != 200) {
logger.error("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
if(i==TIMEOUT_COUNT) {
throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
} catch (SocketTimeoutException e) {
logger.error("读取响应超时,重新读取,次数: "+ (i) + ",响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage(), e);
if(i==TIMEOUT_COUNT) {
throw new SocketTimeoutException("读取响应超时,次数已用完,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
} BufferedReader responseBuffer = null; for(int i=1; i<=TIMEOUT_COUNT; i++){
try{
responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), CHARSET));
break;
} catch (SocketTimeoutException e){
logger.error("读取响应超时,重新读取,次数: "+ (i) +",异常信息: " + e.getMessage(), e);
if(i==TIMEOUT_COUNT) {
throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
} catch (Exception e){
logger.error(e);
if(i==TIMEOUT_COUNT) {
throw e;
}
}
}
String output, result = "";
logger.debug("Output from timedtask Server: \n");
while ((output = responseBuffer.readLine()) != null) {
logger.info(output);
result = output;
}
if(responseBuffer!=null){
responseBuffer.close();
}
//JSONObject obj = new JSONObject();
//obj = JSONObject.parseObject(result);
//System.out.println(obj.toString());
httpConnection.disconnect();
if(result==null || result.trim().isEmpty()){
throw new Exception("系统错误或请求超时,请稍后再试");
}
return result;
} /**
* 发送https请求
* @param url 路径
* @param param 参数
* @return
* @throws Exception
*/
public static String doPostHttps(String url, Map<String, Object> param) throws Exception { URL restServiceURL = new URL(url);
StringBuffer params = new StringBuffer();
if(param!=null && param.size()>0) {
Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> element = it.next();
params.append(element.getKey()).append("=").append(element.getValue()).append("&");
}
if (params.length() > 0) {
String sign = AES.getInstance().encrypt(params.toString(), APP_INTERFACE_SIGN_KEY);
params.append("Sign=" + sign);
}
} logger.info(url + "\n\t原始数据---" + param + "\n\t格式化后数据---" + params);
System.setProperty("jsse.enableSNIEXtension", "false");
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
HttpsURLConnection httpConnection = (HttpsURLConnection) restServiceURL.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setConnectTimeout(15000);
httpConnection.setReadTimeout(500000);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept-Charset", CHARSET);
httpConnection.setSSLSocketFactory(ssf);
PrintWriter printWriter = null; for(int i=0;i< TIMEOUT_COUNT;i++){
try {
printWriter = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), CHARSET));
printWriter.write(params.toString());
break;
}catch(ConnectException e) {
logger.error("连接超时,重新连接,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
if(i== TIMEOUT_COUNT -1){
throw new ConnectException("连接超时,重新连接,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
}
}catch(SocketTimeoutException e){
logger.error("请求超时,重新请求,次数: " + (i + 1) + ",异常信息: " + e.getMessage());
if(i== TIMEOUT_COUNT -1){
throw new SocketTimeoutException("请求超时,请求次数: " + (i + 1) + ",异常信息: " + e.getMessage());
}
} catch(Exception e){
logger.error(e.getMessage());
if(i== TIMEOUT_COUNT -1){
throw new Exception(e.getMessage());
}
} finally {
if(printWriter!=null) {
printWriter.flush();
printWriter.close();
}
}
}
for(int i=0; i< TIMEOUT_COUNT; i++) {
try {
if (httpConnection.getResponseCode() != 200) {
logger.error("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
if(i== TIMEOUT_COUNT -1) {
throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
} catch (SocketTimeoutException e) {
logger.error("读取响应超时,重新读取,次数: "+ (i+1) + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage());
if(i== TIMEOUT_COUNT -1) {
throw new SocketTimeoutException("读取响应超时,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
}
BufferedReader responseBuffer = null;
for(int i=0; i< TIMEOUT_COUNT; i++){
try{
responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), CHARSET));
break;
} catch (SocketTimeoutException e){
logger.error("读取响应超时,重新读取,次数: "+ (i+1) +",异常信息: " + e.getMessage());
if(i== TIMEOUT_COUNT -1) {
throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
} catch (Exception e){
logger.error(e.getMessage());
if(i== TIMEOUT_COUNT -1) {
throw new Exception(e.getMessage());
}
}
}
String output,result = "";
logger.debug("Output from timedtask Server: \n");
while ((output = responseBuffer.readLine()) != null) {
logger.info(output);
result = output;
}
if(responseBuffer!=null){
responseBuffer.close();
}
httpConnection.disconnect();
if(result==null || result.trim().isEmpty()){
throw new Exception("系统错误或请求超时,请稍后再试");
}
return result;
}
}
package test.test; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import org.apache.log4j.Logger; /**
* http服务
*/
public class HttpURLConnectionClient{
private static String CHARSET = "UTF-8";
private static int TIMEOUT_COUNT = 3;//超时次数
private static Logger logger = Logger.getLogger(HttpURLConnectionClient.class);
public static SimpleDateFormat sf_yyyy_mm_dd_hh_mm_ss = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static SimpleDateFormat yyyyMMddHHmmssS = new SimpleDateFormat("yyyyMMddHHmmssS"); /**
* 发送POST http请求
* @param url 路径
* @param param 参数
* @return
* @throws Exception
*/
public static String doPostHttp(String url, Map<String, Object> param) throws Exception {
URL restServiceURL = new URL(url);
StringBuffer params = new StringBuffer();
if(param!=null && param.size()>0) {
Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Object> element = it.next();
params.append((String)element.getKey()).append("=").append(element.getValue()).append("&");
}
}
logger.info(url + "\n\t原始数据---" + param + "\n\t格式化后数据---" + params);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setConnectTimeout(15000);
httpConnection.setReadTimeout(200000);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept-Charset", CHARSET);
PrintWriter printWriter = null;
for(int i=1;i<=TIMEOUT_COUNT;i++){
try {
printWriter = new PrintWriter(new OutputStreamWriter(httpConnection.getOutputStream(), CHARSET));
printWriter.write(params.toString());
break;
}catch(ConnectException e) {
logger.error("连接超时,重新连接,次数: " + (i) + ",异常信息: " + e.getMessage());
if(i==TIMEOUT_COUNT){
throw new ConnectException("连接超时,次数已用完,次数: " + (i) + ",异常信息: " + e.getMessage());
}
}catch(SocketTimeoutException e){
logger.error("请求超时,重新请求,次数: " + (i) + ",异常信息: " + e.getMessage());
if(i==TIMEOUT_COUNT){
throw new SocketTimeoutException("请求超时,次数已用完,请求次数: " + (i) + ",异常信息: " + e.getMessage());
}
} catch(Exception e){
logger.error(e);
if(i==TIMEOUT_COUNT){
throw e;
}
} finally {
if(printWriter!=null) {
printWriter.flush();
printWriter.close();
}
}
}
for(int i=1; i<=TIMEOUT_COUNT; i++) {
try {
if (httpConnection.getResponseCode() != 200) {
logger.error("响应错误,代码: " + httpConnection.getResponseCode() + ",信息: " + httpConnection.getResponseMessage());
if(i==TIMEOUT_COUNT) {
throw new RuntimeException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
} catch (SocketTimeoutException e) {
logger.error("读取响应超时,重新读取,次数: "+ (i) + ",响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage() + ",异常信息: " + e.getMessage(), e);
if(i==TIMEOUT_COUNT) {
throw new SocketTimeoutException("读取响应超时,次数已用完,响应码: " + httpConnection.getResponseCode() + ",响应信息: " + httpConnection.getResponseMessage());
}
Thread.sleep(2000);
}
} BufferedReader responseBuffer = null; for(int i=1; i<=TIMEOUT_COUNT; i++){
try{
responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream()), CHARSET));
break;
} catch (SocketTimeoutException e){
logger.error("读取响应超时,重新读取,次数: "+ (i) +",异常信息: " + e.getMessage(), e);
if(i==TIMEOUT_COUNT) {
throw new SocketTimeoutException("HTTP GET Request Failed with Error codeHandler : " + httpConnection.getResponseMessage());
}
} catch (Exception e){
logger.error(e);
if(i==TIMEOUT_COUNT) {
throw e;
}
}
}
String output, result = "";
logger.debug("Output from Server: \n");
while ((output = responseBuffer.readLine()) != null) {
logger.info(output);
result = output;
}
if(responseBuffer!=null){
responseBuffer.close();
}
httpConnection.disconnect();
if(result==null || result.trim().isEmpty()){
throw new Exception("系统错误或请求超时,请稍后再试");
}
return result;
} public static void main(String[] args){
Map<String,Object> map = new HashMap<String,Object>();
map.put("phoneNum", "15152200001");
map.put("loginpwd", "a123456");
String result = null;
try {
result = doPostHttp("http://192.168.62.207:8080/app/webservice/member/login",map);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
} }
HttpURLConnectionClient的更多相关文章
随机推荐
- ASP.NET MVC file download sample
ylbtech- ASP.NET MVC:ASP.NET MVC file download sample 功能描述:ASP.NET MVC file download sample 2,Techno ...
- docker_usb开发软件部署
1.docker镜像包 (备注:61提供,带桌面版本) rayosx2.0.2.tar 2.paho-mqtt dnf install git -y git clone https://github ...
- 解读Spark Streaming RDD的全生命周期
本节主要内容: 一.DStream与RDD关系的彻底的研究 二.StreamingRDD的生成彻底研究 Spark Streaming RDD思考三个关键的问题: RDD本身是基本对象,根据一定时间定 ...
- angular directive 的controllerAs的用法
原文: https://stackoverflow.com/questions/31857735/using-controlleras-with-a-directive --------------- ...
- 2015 Multi-University Training Contest 1记录
1001 OO's Sequence 分析: 对于例子,能够得到,我们要求的是(1,1)(1,2)(1,3)(1,4)(1,5)(2,2)(2,3)(2,4)(2,5)(3,3)(3,4)(3,5)( ...
- Linux学习笔记 (八)Shell概述
一.什么是Shell? Shell是一个命令行解释器,它为用户提供了一个向Linux内核发送请求以便运行程序的界面系统级程序,用户可以用Shell来启动,挂起,停止甚至是编写一些程序.Shell还是一 ...
- ActiveMQ简述
概述 ActiveMQ是Apache所提供的一个开源的消息系统,全然採用Java来实现.因此.它能非常好地支持J2EE提出的JMS(Java Message Service,即Java消息服务)规范. ...
- Linux下使用Fastboot给手机刷ROM
前言 一直在刷机.失败.刷机.失败中,还好今天有个任务能够使用fastboot刷机.好开心,最终不用切换系统了.(话说好久没有写代码了,身为一个互联网程序猿,不写代码我easy紧张). 开发环境 Ub ...
- [1-5] 把时间当做朋友(李笑来)Chapter 5 【小心所谓成功学】 摘录
有一个事实非常简单,却令人难以接受.这世界上所有的资源并非平均分布在每一个人的身上,能够比较接近地表示这种分布情况的数学曲线叫做“正态分布曲线”(Normal Distribution Curve) ...
- Oracle创建DataBase Links
-- Drop existing database link drop database link GJA_CFMDM_LINK;-- Create database link create data ...