13,100
社区成员
发帖
与我相关
我的任务
分享
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlToHtml {
public static void main(String[] args) {
String content = readUrlContent("http://www.investide.cn/edm/index.do");
//http://www.investide.cn/edm/index.do用的是gbk编码
try{
content = new String(content.getBytes(), "GBK");
System.out.println(content);
if (!(writeFile(content, "/home/mush/1.html")))
{
System.out.println("文件生成失败");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static String readUrlContent(String url)
{
StringBuffer sb = new StringBuffer();
try
{
String strLine;
URL urlObj = new URL(url);
InputStream streamObj = urlObj.openStream();
InputStreamReader readerObj = new InputStreamReader(streamObj,"GBK");
BufferedReader buffObj = new BufferedReader(readerObj);
while ((strLine = buffObj.readLine()) != null)
sb.append(strLine + "\r");
buffObj.close();
} catch (MalformedURLException e) {
System.err.println("url error");
} catch (IOException e) {
System.out.println("IO error");
}
return sb.toString();
}
public static boolean writeFile(String str, String filePath) {
boolean result = true;
try {
//FileWriter fw = new FileWriter(filePath);
Writer fw = new OutputStreamWriter(new FileOutputStream (filePath),"GBK");
fw.write(str);
fw.close();
} catch (IOException e) {
result = false;
System.out.println("写文件失败");
}
return result;
}
}
import java.io.IOException;
import javax.servlet.*;
public class SetCharactorEncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)throws IOException, ServletException {
request.setCharacterEncoding("GBK");
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
XML code
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>cn.ac.sict.ietd.util.SetCharactorEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>