项目中须要与第三方系统交互,而交互的方式是XML报文形式,因此会用到HttpConnection与第三方系统链接交互,使用起来并不复杂,可是有几点须要注意的:服务器
1.乱码的问题解决网络
2.超时的设置,注意这个问题很严重,当你网络正常的时候看不出区别,可是当你网络不正常的时候,没有设置超时时间会致使你的系统一直尝试链接三方系统,可能会致使系统延迟好久因此必定记得处理,一个应用的效率很重要。app
附上代码:编码
HttpURLConnection urlConnection = null; OutputStream outputStream = null; BufferedReader bufferedReader = null; try { URL httpUrl = new URL(url);//建立对应的url对象 urlConnection = (HttpURLConnection) httpUrl.openConnection();//HttpConnection对象,这一步只是建立了对象并无链接远程服务器 urlConnection.setDoInput(true);//容许读 urlConnection.setDoOutput(true);//容许写 urlConnection.setRequestMethod("POST");//请求方式 urlConnection.setRequestProperty("Pragma:", "no-cache"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "text/xml");//请求的消息格式 urlConnection.setConnectTimeout(6000);//很重要,设置超时时间 urlConnection.connect();//真正的链接服务器 outputStream = urlConnection.getOutputStream(); byte[] bytes = xml.getBytes("GBK");//这里的xml即为你想传递的值,由于项目中与三方交互要用GBK编码因此转换为GBK outputStream.write(bytes);//传递值 StringBuffer temp = new StringBuffer(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); Reader rd = new InputStreamReader(in,"GBK");//服务器返回的也是GBK编码格式的数据。 int c = 0; while ((c = rd.read()) != -1) { temp.append((char) c); }//其实能够使用String str =new String(response.getBytes(),"GBK");这种方式解决乱码问题,可是此次项目中使用这种方式并无解决,因此干脆一个个字节的转。 in.close(); return temp.toString(); } catch (MalformedURLException e) { log.error("connect server failed,cause{}", e.getMessage()); } catch (IOException e) { log.error("io execute failed,cause{}", e.getMessage()); throw e; } finally { try { if (!Arguments.isNull(outputStream)) { outputStream.close(); } if (!Arguments.isNull(bufferedReader)) { bufferedReader.close(); } //该处理的资源须要处理掉,该关闭的须要关闭 } catch (IOException e) { log.error("io close failed , cause{}", e.getMessage()); } }
交互很简单 可是细节很重要。。。。url