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的更多相关文章
随机推荐
- PHP文件包含漏洞总结
0x00 前言 PHP文件包含漏洞的产生原因是在通过PHP的函数引入文件时,由于传入的文件名没有经过合理的校验,从而操作了预想之外的文件,就可能导致意外的文件泄露甚至恶意的代码注入. 最常见的就属于本 ...
- photo sphere viewer使用图像数据替代路径来生成全景图
photo sphere viewer是一个js库,用来将全景图片生成360度的全景图像,但是其要求传入的是个路径.如何使用数据代替路径生成图像. 我采用的方法是用img标签生成图像,然后调用img. ...
- BIO的简单Demo
package jesse.test1; import java.io.BufferedReader; import java.io.IOException; import java.io.Input ...
- 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)( ...
- 利用Bootstrap制作一个流行的网页
首先是html承载内容: <!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset ...
- dubbo笔记
使用Maven打包依赖项,启动时从本地jar中读取dubbo.xsd 最近项目用到dubbo,打包启动时报错 Failed to read schema document from http://co ...
- Vue 组件开发demo
1.代码地址 github:https://github.com/MengFangui/VueComponentDemo- 2.关键代码 (1)main.js //引入vue import Vue f ...
- 页面找不到js方法的原因,关于EasyUI
有时EasyUI中datagride写法不正确,会导致无法加载页面上其他的js方法.datagride中的逗号是一个也不能多.一定要注意: 例如以下代码中标红的逗号就会导致后边的js不能正常加载. c ...
- 由于删除DBF文件报错 —— ORA-01033: ORACLE initialization or shutdown in progress
由于移动或删除DBF文件报错:ORA-01033: ORACLE initialization or shutdown in progress 原因:一般该类故障通常是由于移动文件而影响了数据库日 ...
- EPH接收Event Hub Message
简介: 使用Python SDK,基于EPH方式接收Azure Event Hub中存储的message,EventProcessorHost()中使用Azure Storage存储offerset等 ...