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 classHttpRequestUtils {14

15 //default time out setting , half minute

16 private static final int defaultTimeOut = 30 * 1000;17

18 private static voidvalidateUrl(String url) {19 if (!URLUtils.isUseHttpProtocol(url)) {20 throw newjava.lang.IllegalArgumentException(String.format(21 "The URL %s is illegal", url));22 }23 }24

25 public static String doGet(String url, String charSetName, inttimeOut)26 throws Exception {27 validateUrl(url);28 try{29 URL ur = newURL(url);30 URLConnection con =ur.openConnection();31 con.setConnectTimeout(timeOut);32 con.setReadTimeout(timeOut);33 BufferedReader rd = new BufferedReader(newInputStreamReader(con34 .getInputStream(), charSetName));35 StringBuilder sb = newStringBuilder();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 returnsb.toString();49 } catch(Exception e) {50 throw newException(e);51 }52 }53

54 public staticString doGet(String url, String charSetName) throws Exception {55 returndoGet(url, charSetName, defaultTimeOut);56 }57

58 public staticString doGet(String url) throws Exception {59 returndoGet(url, UtilConstants.DEFAULT_CHARSET, defaultTimeOut);60 }61

62 public static void doGetFile(String url, inttimeOut, String fullFileName)63 throws Exception {64 validateUrl(url);65 InputStream is = null;66 OutputStream os = null;67 try{68 URL ur = newURL(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 intlen;79

80 os = newFileOutputStream(fullFileName);81 while ((len = is.read(bs)) != -1) {82 os.write(bs, 0, len);83 }84 } catch(Exception e) {85 throw newException(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, inttimeOut)103 throws Exception {104 validateUrl(url);105 InputStream is = null;106 try{107 URL ur = newURL(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 newException(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, Mapparameters,126 inttimeOut, String charSetName) throws Exception {127 //validate

128 validateUrl(url);129

130 //generate post data form parameters

131 StringBuilder sb = newStringBuilder();132 for (Map.Entrykv : 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 = newURL(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(newInputStreamReader(con161 .getInputStream(), charSetName));162 StringBuilder rsb = newStringBuilder();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 returnrsb.toString();178 } catch(Exception e) {179 throw newException(e);180 }181 }182

183 public static String doPost(String url, Mapparameters,184 inttimeOut) throws Exception {185 returnHttpRequestUtils186 .doPost(url, parameters, timeOut, UtilConstants.DEFAULT_CHARSET);187 }188

189 public static String doPost(String url, Mapparameters)190 throws Exception {191 returnHttpRequestUtils.doPost(url, parameters, defaultTimeOut,192 UtilConstants.DEFAULT_CHARSET);193 }194

195 public static int doHead(String url, inttimeOut) throws Exception {196 validateUrl(url);197 try{198 URL ur = newURL(url);199 HttpURLConnection con =(HttpURLConnection) ur.openConnection();200 con.setConnectTimeout(timeOut);201 returncon.getResponseCode();202 } catch(Exception e) {203 throw newException(e);204 }205 }206

207 public static intdoHead(String url) throws Exception {208 returndoHead(url, defaultTimeOut);209 }210

211 public staticJSONObject doPostByJson(String httpUrl, JSONObject jsonObject) throws IOException {212 return doPostByJson(httpUrl, jsonObject, 20000);213 }214

215 public staticJSONObject 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 = newURL(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("\n","").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 returnreturnObj;276 }277

278

279 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值