日期:2014-05-18 浏览次数:20738 次
public class XmlTransfer{ private String urlAddr; private String xmlStr; HttpURLConnection urlCon = null; public XmlTransfer(String _urlAddr,String _xmlStr) { this.urlAddr = _urlAddr; this.xmlStr = _xmlStr; } public InputStream get() throws Exception { if(urlCon==null){urlCon=getUrlConnection();} if(urlCon==null){throw new Exception("连接失败");} PrintWriter out = new PrintWriter(urlCon.getOutputStream()); urlCon.disconnect(); InputStream fin1 = urlCon.getInputStream(); return fin1; } private HttpURLConnection getUrlConnection(){ try{ URL url = new URL(urlAddr); URLConnection conn = url.openConnection(); urlCon = (HttpURLConnection)conn; urlCon.setRequestProperty("Content-type", "text/html;charset=utf-8"); urlCon.setDoOutput(true); urlCon.setRequestMethod("GET"); urlCon.setUseCaches(false); } catch (MalformedURLException mex) { mex.printStackTrace(); } catch (ProtocolException pex) { pex.printStackTrace(); } catch (IOException iex) { iex.printStackTrace(); } return urlCon; } public String getHttp( String strURL ){ XmlTransfer xt=new XmlTransfer(strURL,""); StringBuffer sb = new StringBuffer(); try{ InputStream is = xt.get(); byte[] b = new byte[1024]; int iCount = 0; while ((iCount = is.read(b)) > 0) { sb.append(new String(b, 0, iCount)); } }catch(Exception e){ sb.append("An error occurs in XmlTransfer.getHttp\n"); sb.append(e.getMessage()); } return (sb.toString()); } }
StringBuffer temp = new StringBuffer(); InputStream in = new BufferedInputStream(urlCon.getInputStream();); Reader rd = new InputStreamReader(in,"UTF-8"); int c = 0; while ((c = rd.read()) != -1) { temp.append((char) c); } in.close(); temp.toString();//得到xml
------解决方案--------------------
你一个过滤器就ok!
package com.shop.filter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
/**************************************************
* author:East
* date:2008-6-13
* note: EncodingFilter用来解决中文的乱码
**************************************************/
public class EncodingFilter extends HttpServlet implements Filter {
private FilterConfig filterConfig;
//Handle the passed-in FilterConfig
public void init(FilterConfig filterConfig) throws Servle