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的更多相关文章
随机推荐
- 手把手教你调试Entity Framework 6源码
0 摘要 本文讲述在Visual Studio 2013(VS 2013)下调试Entity Framework 6(EF 6)源码的配置过程.原则上,VS 2012也适用. 之前打算编写<E ...
- MyEclipse中快捷键
------------------------------------- MyEclipse 快捷键1(CTRL) ------------------------------------- Ctr ...
- PhantomJS用法示例
收录待用,修改转载已取得腾讯云授权 前言 大家有没有发现之前我们写的爬虫都有一个共性,就是只能爬取单纯的html代码,如果页面是JS渲染的该怎么办呢?如果我们单纯去分析一个个后台的请求,手动去摸索JS ...
- [Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))
When combining multiple State ADT instances that depend on the same input, using chain can become qu ...
- 倍福TwinCAT(贝福Beckhoff)常见问题(FAQ)-Switch Case语句是否会自动跳转到下一个
在C#中,每一个case后面必须有break,所以输出1,也就是如果a=0,则只会执行case=0的那一段,当等于1之后不会继续. 在TwinCAT中,虽然CASE语句没有break,但是实际上不 ...
- 单用户模式下mount -o remount,rw / 有大用途
我们的Linux系统在无法启动时候,通常需要进入单用户模式下进行修改一些配置文件,或调整一些参数方可.但是在进入单用户模式后,我们的/文件系统是只读模式,无法进行修改,那么这个时候我们就需要用到一条命 ...
- lua类库 middleclass学习笔记
middleclass使在lua中面象对象变的简单 抄了一遍他的示例代码运行着试了试,基本懂了 local class = require 'middleclass' --类的继承 Person = ...
- androidstudio新建项目中在布局文件中不显示title的方法
在androidstudio新建项目的时候,在布局文件里有时候会出现如下情况: 上面的标题栏非常碍眼,要想隐藏标题栏的话,可以在Manifest文件的theme标签里进行配置,自定义一个theme,加 ...
- 64位WinRAR5.0破解
在WinRAR安装文件夹下新建文件rarreg.key,用记事本打开rarreg.key把上面的内容复制到记事本再把rarreg.key里保存即可,文件内容如下: RAR registration d ...
- HTML输入验证提示信息
1.oninvali事件通过setCustomValidity方法来自定义提示信息 <form action=""> <label> 数字: <inp ...