模拟POST 返回值为乱码
环境 : mysql 4.0.12数据库 + myeclipse7.0 + jdk 1.6U17
问题 : 我从数据库读出来的数据是乱码
如下:
过程:
1. 我用java编写的代码.
2. 这个版本的mysql 默认的字符集是 ISO8859-1
3. 我获取的方式是 通过 应用程序 模拟 POST 方法来获取的数据库的值.
代码如下:
// 调用POST方法
public static String connect(String sqltype,String sql,String gGebug)
{
HttpClient client = new HttpClient();
HttpMethod httpPost =getPostMethod(sqltype, sql,gGebug);
//HttpMethod httpPost =getGetMethod();
client.getHostConfiguration().setHost("192.168.1.6",88,"http");
try {
int status = client.executeMethod(httpPost);
if(status==200)
{
InputStream its=httpPost.getResponseBodyAsStream();
BufferedReader bf = new BufferedReader(new InputStreamReader((its)));
String line="";
String[] val=null;
while((line =bf.readLine())!= null)
{
// select sql return field value.
if("S".equals(sqltype))
{
if(line.contains("::"))
{
if(! line.contains("$$"))
{
String temp =line.replace("::", "!");
val = temp.split("!");
return val[1];
}
else
{
// ...
}
}
}
// return value : update num
if("U".equals(sqltype))
{
if(line.contains("$$"))
{
String temp =line.replace("$$", "!");
val = temp.split("!");
return val[1];
}
//return val;
}
// insert sql return success result.
if("I".equals(sqltype))
{
if(line.contains("$$"))
{
String temp =line.replace("$$", "!");
val = temp.split("!");
return val[0];
}
}
//System.out.println(EncodeTransfer.gb2iso(line));
}
}
else
{
System.out.println("fail return value "+status);
}
return null;
} catch (HttpException e) {
e.printStackTrace(System.err);
} catch (IOException e) {
e.printStackTrace(System.err);
}finally{
httpPost.releaseConnection();
}
return null;
}
//getPostMethod 模拟post的方法
private static HttpMethod getPostMethod(String exetype,String exesql,String debug)
{
PostMethod post = new PostMethod("/bug/include/DB_API.php");
NameValuePair sqltype = new NameValuePair("gSqlType",exetype);
NameValuePair sql = new NameValuePair("gSql",exesql);
NameValuePair gdebug = new NameValuePair("gDebug",debug);
post.setRequestBody(new NameValuePair[] {sqltype,sql,gdebug});
return post;
}
// 主方法
public static void main(String[] args) {
// TODO Auto-generated method stub
String sql = "select bba02 from bba where bba01=107";
try {
// 我获得的从数据库读出来的是UTF-8 但是这样转换还是出来的不正常 如:锟脚讹拷锟侥硷拷锟斤拷锟斤拷系统
System.out.println(new String(connect("S",s,"1").getBytes("UTF-8"),"GBK"));
// 这是没有转换 的结果 如: �Ŷ��ļ�����ϵͳ
System.out.println(connect("S",s,"1"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}