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的更多相关文章
随机推荐
- Linux下sqlite3编程
---------------------------------------------------------------------------------------------------- ...
- Linux tftp配置
TFTP是用来下载远程文件的最简单网络协议,它其于UDP协议而实现. xinetd(eXtended InterNET services daemon)是新一代的网络守护进程服务程序,又叫超级INTE ...
- Java solr 索引数据增删改查
具体代码如下: import java.io.IOException; import java.util.*; import org.apache.solr.client.solrj.SolrClie ...
- Kinect 1.8 体感开发,手势,姿态(Pose) 捕捉判断方法以及一些辅方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- ionic在iOS中打包失败
在ios中打包失败,遇上这样的错误 解决办法,查看index.html的权限是否是只读状态,如果是,改成可读可写,再次打包重试,成功!
- 基于Vue开发的tab切换组件
github地址:https://github.com/MengFangui/VueTabSwitch 1.index.html <!DOCTYPE html> <html lang ...
- Servlet基础梳理(四)
本篇说一下session和路径的问题. session: 是一种在server端保存http状态信息的方案.眼下有两种实现方式:基于Cookie或者URL重写. 基于cookie:第一次訪问serve ...
- android 开机自启动的几种方法,监听不到RECEIVE_BOOT_COMPLETED的处理办法
第一种: 监控RECEIVE_BOOT_COMPLETED,即开机启动事件 另外一种: 监控sd卡mount事件 开机总会扫描sd卡吧? 监控sd卡事件也有类似开机启动效果.特别app安装在sd卡 ...
- NodeJS在CentOs7下安装
node下载地址:https://nodejs.org/en/download/ 1.安装gcc $ yum install gcc-c++ 2.解压最新版本 $ mkdir /usr/local/n ...
- SGU180:Inversions(树状数组)
There are N integers (1<=N<=65537) A1, A2,.. AN (0<=Ai<=10^9). You need to find amount o ...