关于使用java从http接口取数据保存到本地文件的中文乱码处理
要做到如下几点:
1. 取接口数据,要注意加入编码设置与接口文件本身的编码设置一致,才能取得正确的数据
注意如下的: ins =new InputStreamReader(connection.getInputStream(),"GBK");
必须加入第二个编码格式参数:参数的值与接口返回的数据的编码格式一致
/**
* 从某个接口取返回数据内容
* @param url
* @return
*/
public static String fileGetContents(String strUrl) throws IOException {
URL url1 = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
InputStreamReader ins = null ;
try {
url1 = new URL(strUrl);
connection = (HttpURLConnection) url1.openConnection();
connection.setConnectTimeout(2*1000);
connection.setReadTimeout(2*1000);
connection.connect();
ins =new InputStreamReader(connection.getInputStream(),"GBK");
reader = new BufferedReader(ins);
StringBuffer sb = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line+ "\n");
}
return sb.toString();
} catch (IOException e) {
System.out.println("Error getURL:" + e);
System.out.println("Error getURL:" + strUrl);
}finally
{
if(ins != null)
{
try {
ins.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(reader != null)
{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection != null)
{
connection.disconnect();
}
}
return null;
}
2. 写文件处理:
要注意写入文件本身实际需要的编码格式:
注意:OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"GB2312"); 这句
public static void writeFile(String fileName, String fileContent)
{
try
{
File f = new File(fileName);
if (!f.exists())
{
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"GB2312");
BufferedWriter writer=new BufferedWriter(write);
writer.write(fileContent);
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
3. 接口方编码设置:
如接口为http://www.test.com/getdata.jsp
假设如下:
<%@ page language="java" contentType="text/html; charset=GB2312"
pageEncoding="GB2312">
总的来说就是各个地方都采用一致的编码就可以避免讨厌头疼的中文编码乱码问题的发生。