远程接口调用封装工具
public class RemoteInvoker { private final static int CONNECT_TIME_OUT_TIME = 1000*30; //30s 连接超时时间 private final static int READ_TIME_OUT_TIME = 1000*30; //30s 读超时 private final static String CHARSET_NAME = "utf-8"; /** * 远程调用 * @param url 目标url * @param map 参数列表 Map<String,String> * @param requestMethod GET,POST * @return */ public static RemoteResultDto getRemote(String url,Map<String,String> map, RequestMethod requestMethod,String charset){ if(StringUtils.isBlank(url)) return null; if(StringUtils.isEmpty(charset)){ charset = CHARSET_NAME; } RemoteResultDto resultDto = new RemoteResultDto(); BufferedReader bufferedReader = null; OutputStreamWriter outputStreamWriter = null; String params = null; try{ String targetUrl = url; URLConnection urlConnection ; params = getParams(map); if(requestMethod.equals(RequestMethod.POST)){ //POST urlConnection = new URL(url).openConnection(); setCommonProperties(urlConnection); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(CONNECT_TIME_OUT_TIME); //连接超时时间 urlConnection.setReadTimeout(READ_TIME_OUT_TIME); outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), charset); if(!StringUtils.isBlank(params)){ outputStreamWriter.write(params); } outputStreamWriter.flush(); }else{ //GET targetUrl += StringUtils.isBlank(params) ? "" : "?" + params; urlConnection = new URL(targetUrl).openConnection(); setCommonProperties(urlConnection); urlConnection.setConnectTimeout(CONNECT_TIME_OUT_TIME); //连接超时时间 urlConnection.setReadTimeout(READ_TIME_OUT_TIME); urlConnection.connect(); } bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),charset)); String line = null; StringBuffer content = new StringBuffer(); while((line = bufferedReader.readLine()) != null) { content.append(line); } resultDto.setResultStatus(RemoteResultStatus.SUCCESS); resultDto.setResult(content.toString()); }catch (SocketTimeoutException e){ DevLog.error(RemoteInvoker.class,String.format("[getRemote] err_1 SocketTimeoutException=%s,url=%s,params=%s" + "",e.getMessage(),url,params),e); if("Read timed out".equals(e.getMessage())) { resultDto.setResultStatus(RemoteResultStatus.READ_TIME_OUT); }else resultDto.setResultStatus(RemoteResultStatus.CONNECT_TIME_OUT); }catch (Exception e){ DevLog.error(RemoteInvoker.class,String.format("[getRemote] err_2 SocketTimeoutException=%s,url=%s,params=%s" + "",e.getMessage(),url,params),e); resultDto.setResultStatus(RemoteResultStatus.EXCEPTION); } finally { try{ if(null != bufferedReader) { bufferedReader.close(); } if(null != outputStreamWriter) { outputStreamWriter.close(); } }catch (Exception e){ DevLog.error(RemoteInvoker.class,"/getRemote.finally exception = "+e.getMessage(),e); } } return resultDto; } /** * 遍历组装参数 * @param map * @return */ private static String getParams(Map<String,String> map) throws IOException{ if(map == null) return null; StringBuffer sbf = new StringBuffer(); Iterator it = map.entrySet().iterator(); while (it.hasNext()){ Map.Entry entry = ( Map.Entry)it.next(); if(null != entry.getValue()){ //注意转码,URL参数里面不能有特殊符号或空格 String value = java.net.URLEncoder.encode(entry.getValue().toString(),"UTF-8"); sbf.append(entry.getKey().toString()).append("=").append(value).append("&"); } } return sbf.toString(); } /** * 设置通用属性 * @param urlConnection */ private static void setCommonProperties(URLConnection urlConnection){ urlConnection.setRequestProperty("accept", "*/*"); urlConnection.setRequestProperty("connection", "Keep-Alive"); urlConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); urlConnection.setRequestProperty("Accept-Charset", "utf-8"); //把用户加密串信息,保存到header中 String jtwsInfo = UserContextUtils.getCurrentUser() == null ? "": UserContextUtils.getCurrentUser().getLoginTokenSign(); urlConnection.setRequestProperty("JTWS_INFO", jtwsInfo); //urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=GBK"); //urlConnection.setRequestProperty("Content-Type", "application/json;charset=GBK"); } }
以上为远程访问接口访问类封装
RemoteResultDto实例类
public class RemoteResultDto { //访问接口状态 是否调通接口 private RemoteResultStatus resultStatus; //接口放回信息 private String result; public RemoteResultStatus getResultStatus() { return resultStatus; } public void setResultStatus(RemoteResultStatus resultStatus) { this.resultStatus = resultStatus; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
RemoteResultStatus实例类 接口状态
public enum RemoteResultStatus { SUCCESS, EXCEPTION, CONNECT_TIME_OUT, SEND_SMS_NUM_OUT, READ_TIME_OUT; }