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的更多相关文章
随机推荐
- 转: HTTP Live Streaming直播(iOS直播)技术分析与实现
			
http://www.cnblogs.com/haibindev/archive/2013/01/30/2880764.html HTTP Live Streaming直播(iOS直播)技术分析与实现 ...
 - android:  android中dip、dp、px、sp和屏幕密度
			
android中dip.dp.px.sp和屏幕密度 转自:http://www.cnblogs.com/fbsk/archive/2011/10/17/2215539.html 1. dip: dev ...
 - jQuery (DOM篇)
			
1.DOM节点的创建 创建元素节点: 常见的就是直接把这个节点的结构给通过HTML标记字符串描述出来,通过$()函数处理,$("html结构") $("<div&g ...
 - iOS 程序进入后台,包含用户上拉快捷菜单导致程序失去活跃的研究
			
今日在使用某App时候,突然发现上拉菜单.程序视频扔在播放,咦!引起了我的兴趣. 首先,列出两个方法, 第一个方法是AppDelegate的代理.当程序进入后台时候调用 - (void)applica ...
 - 【Python3 爬虫】08_正则表达式(元字符与语法)
			
元字符表 符号 说明 示例 . 表示任意字符 'abc' >>>'a.c' >>>结果为:'abc' ^ 表示字符开头 'abc' >>> ...
 - 【Java】Java_08 字符型与布尔值
			
1.字符型(2个字节) 单引号用来表示字符常量.例如‘A’是一个字符,它与“A”是不同的,“A”表示含有一个字符的字符串 char 类型用来表示在Unicode编码表中的字符 Unicode编码被设计 ...
 - HDU 4925 Apple Tree(推理)
			
HDU 4925 Apple Tree 题目链接 题意:给一个m*n矩阵种树,每一个位置能够选择种树或者施肥,假设种上去的位置就不能施肥,假设施肥则能让周围果树产量乘2.问最大收益 思路:推理得到肯定 ...
 - python学习日记:np.newaxis
			
import numpy as np label = np.array([[1,2,3,4],[5,6,7,8]])print (label.shape)label = label[np.newaxi ...
 - Problem-1001:Sum Problem
			
Sum Problem Sample code : #include <stdio.h> int main() { int i,n; int sum; while(scanf(" ...
 - 用JS将json日期格式化成正常日期
			
function ChangeDateFormat(cellval) { var date = new Date(parseInt(cellval.replace(&qu ...