java服务器访问其他服务器工具类编写

java服务器访问其他服务器工具类编写
适合各种消息推送及微服务交互
  1 package com.xiruo.medbid.components;
  2 
  3 import com.xiruo.medbid.util.UtilConstants;
  4 import net.sf.json.JSONObject;
  5 
  6 import java.io.*;
  7 import java.net.HttpURLConnection;
  8 import java.net.MalformedURLException;
  9 import java.net.URL;
 10 import java.net.URLConnection;
 11 import java.util.Map;
 12 
 13 public class HttpRequestUtils {
 14 
 15     // default time out setting , half minute
 16     private static final int defaultTimeOut = 30 * 1000;
 17 
 18     private static void validateUrl(String url) {
 19         if (!URLUtils.isUseHttpProtocol(url)) {
 20             throw new java.lang.IllegalArgumentException(String.format(
 21                     "The URL %s is illegal", url));
 22         }
 23     }
 24 
 25     public static String doGet(String url, String charSetName, int timeOut)
 26             throws Exception {
 27         validateUrl(url);
 28         try {
 29             URL ur = new URL(url);
 30             URLConnection con = ur.openConnection();
 31             con.setConnectTimeout(timeOut);
 32             con.setReadTimeout(timeOut);
 33             BufferedReader rd = new BufferedReader(new InputStreamReader(con
 34                     .getInputStream(), charSetName));
 35             StringBuilder sb = new StringBuilder();
 36             try {
 37                 int k = rd.read();
 38                 while (k != -1) {
 39                     sb.append((char) k);
 40                     k = rd.read();
 41                 }
 42             } catch (Exception ee) {
 43             } finally {
 44                 if (rd != null) {
 45                     rd.close();
 46                 }
 47             }
 48             return sb.toString();
 49         } catch (Exception e) {
 50             throw new Exception(e);
 51         }
 52     }
 53 
 54     public static String doGet(String url, String charSetName) throws Exception {
 55         return doGet(url, charSetName, defaultTimeOut);
 56     }
 57 
 58     public static String doGet(String url) throws Exception {
 59         return doGet(url, UtilConstants.DEFAULT_CHARSET, defaultTimeOut);
 60     }
 61 
 62     public static void doGetFile(String url, int timeOut, String fullFileName)
 63             throws Exception {
 64         validateUrl(url);
 65         InputStream is = null;
 66         OutputStream os = null;
 67         try {
 68             URL ur = new URL(url);
 69             URLConnection con = ur.openConnection();
 70             con.setConnectTimeout(timeOut);
 71             con.setReadTimeout(timeOut);
 72 
 73             is = con.getInputStream();
 74 
 75             // 1K cache
 76             byte[] bs = new byte[1024];
 77             // length
 78             int len;
 79 
 80             os = new FileOutputStream(fullFileName);
 81             while ((len = is.read(bs)) != -1) {
 82                 os.write(bs, 0, len);
 83             }
 84         } catch (Exception e) {
 85             throw new Exception(e);
 86         } finally {
 87             if (os != null) {
 88                 try {
 89                     os.close();
 90                 } catch (IOException e) {
 91                 }
 92             }
 93             if (is != null) {
 94                 try {
 95                     is.close();
 96                 } catch (IOException e) {
 97                 }
 98             }
 99         }
100     }
101 
102     public static InputStream doGetStream(String url, int timeOut)
103             throws Exception {
104         validateUrl(url);
105         InputStream is = null;
106         try {
107             URL ur = new URL(url);
108             URLConnection con = ur.openConnection();
109             con.setConnectTimeout(timeOut);
110             con.setReadTimeout(timeOut);
111             is = con.getInputStream();
112             return is;
113         } catch (Exception e) {
114             throw new Exception(e);
115         } finally {
116             if (is != null) {
117                 try {
118                     is.close();
119                 } catch (Exception unusede) {
120                 }
121             }
122         }
123     }
124 
125     public static String doPost(String url, Map<String, String> parameters,
126                                 int timeOut, String charSetName) throws Exception {
127         // validate
128         validateUrl(url);
129 
130         // generate post data form parameters
131         StringBuilder sb = new StringBuilder();
132         for (Map.Entry<String, String> kv : parameters.entrySet()) {
133             sb.append(kv.getKey());
134             sb.append("=");
135             sb.append(URLUtils.decode(kv.getValue()));
136             sb.append("&");
137         }
138         if (sb.length() > 0) {
139             sb.deleteCharAt(sb.length() - 1);
140         }
141         byte[] postData = BytesUtils.toBytes(sb);
142         try {
143             URL ur = new URL(url);
144             URLConnection con = ur.openConnection();
145 
146             // setting
147             con.setConnectTimeout(timeOut);
148             con.setReadTimeout(timeOut);
149             con.setDoInput(true);
150             con.setDoOutput(true);
151             con.setUseCaches(false);
152             con.setDefaultUseCaches(false);
153 
154             con.setRequestProperty("Content-Length", postData.length + "");
155             OutputStream os = con.getOutputStream();
156 
157             os.write(postData);
158             os.flush();
159             os.close();
160             BufferedReader rd = new BufferedReader(new InputStreamReader(con
161                     .getInputStream(), charSetName));
162             StringBuilder rsb = new StringBuilder();
163             try {
164                 int k = rd.read();
165                 while (k != -1) {
166                     rsb.append((char) k);
167                     k = rd.read();
168                 }
169             } catch (Exception ee) {
170             } finally {
171                 try {
172                     rd.close();
173                 } catch (Exception e) {
174 
175                 }
176             }
177             return rsb.toString();
178         } catch (Exception e) {
179             throw new Exception(e);
180         }
181     }
182 
183     public static String doPost(String url, Map<String, String> parameters,
184                                 int timeOut) throws Exception {
185         return HttpRequestUtils
186                 .doPost(url, parameters, timeOut, UtilConstants.DEFAULT_CHARSET);
187     }
188 
189     public static String doPost(String url, Map<String, String> parameters)
190             throws Exception {
191         return HttpRequestUtils.doPost(url, parameters, defaultTimeOut,
192                 UtilConstants.DEFAULT_CHARSET);
193     }
194 
195     public static int doHead(String url, int timeOut) throws Exception {
196         validateUrl(url);
197         try {
198             URL ur = new URL(url);
199             HttpURLConnection con = (HttpURLConnection) ur.openConnection();
200             con.setConnectTimeout(timeOut);
201             return con.getResponseCode();
202         } catch (Exception e) {
203             throw new Exception(e);
204         }
205     }
206 
207     public static int doHead(String url) throws Exception {
208         return doHead(url, defaultTimeOut);
209     }
210 
211     public static JSONObject doPostByJson(String httpUrl, JSONObject jsonObject) throws IOException {
212         return doPostByJson(httpUrl, jsonObject, 20000);
213     }
214 
215     public static JSONObject doPostByJson(String httpUrl, JSONObject jsonObject, Integer timeout) throws IOException {
216         StringBuffer sb = null;
217         HttpURLConnection connection=null;
218         OutputStreamWriter out=null;
219         BufferedReader reader=null;
220         JSONObject returnObj=null;
221         try {
222             //创建连接
223             URL url = new URL(httpUrl);
224             connection = (HttpURLConnection) url.openConnection();
225             connection.setDoOutput(true);
226             connection.setDoInput(true);
227             connection.setRequestMethod("POST");
228             connection.setUseCaches(false);
229             connection.setInstanceFollowRedirects(true);
230             if (null != timeout) {
231                 connection.setReadTimeout(60 * 1000);
232             } else {
233                 connection.setReadTimeout(timeout);
234             }
235 //            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
236             connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
237             connection.connect();
238 
239             //POST请求
240             out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
241             System.out.println("请求参数:"+jsonObject.toString());
242             out.write(jsonObject.toString());
243             out.flush();
244 
245             //读取响应
246             reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
247             String lines;
248             sb = new StringBuffer("");
249             while ((lines = reader.readLine()) != null) {
250                 sb.append(lines);
251             }
252             System.out.println("响应参数:"+sb);
253             if(sb.length()>0){
254                 returnObj= JSONObject.fromObject(sb.toString().replaceAll("
","").replaceAll("null",""null""));
255             }
256             // 断开连接
257         } catch (MalformedURLException e) {
258             // TODO Auto-generated catch block
259             e.printStackTrace();
260         } catch (UnsupportedEncodingException e) {
261             // TODO Auto-generated catch block
262             e.printStackTrace();
263         } finally {
264             if(out!=null){
265                 out.flush();
266                 out.close();
267             }
268             if(reader!=null){
269                 reader.close();
270             }
271             if(connection!=null){
272                 connection.disconnect();
273             }
274         }
275         return returnObj;
276     }
277 
278 
279 }
调用
JSONObject response = HttpRequestUtils.doPostByJson(url, json);

原文地址:https://www.cnblogs.com/180308-new-file/p/8993953.html