同样是对temp 进行new String(temp.toString().getBytes(), ecod)操作,在测试的main方法中可以正常编码获得中文字符,在启动项目后调用时却会出现乱码的情况,请问这是什么原因?
测试环境 win7,项目与tomcat皆用 utf8,request and response 也是指定了utf8的编码
后来发现,不需要在lines = new
String(lines.getBytes());这指定编码,只需要在前面红色地方加上就可以了,搞了半天,头都大了
public static Object getPostRestfulResult(String url,
Map data) {
StringBuffer sb = new StringBuffer();
Object obj = null;
try {
URL restServiceURL = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection)
restServiceURL.openConnection();
// 设置http连接属性
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST"); // 可以根据需要 提交
// GET、POST、DELETE、INPUT等http提供的功能
httpConnection.setUseCaches(false);//设置缓存
httpConnection.setInstanceFollowRedirects(true);
httpConnection.setRequestProperty("accept", "*/*");
httpConnection.setRequestProperty("connection",
"Keep-Alive");
// 设置http头 消息
//
httpConnection.setRequestProperty("Content-Type","application/json");
// 设定 请求格式 json,也可以设定xml格式的
httpConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// connection.setRequestProperty("Content-Type", "text/xml");
//设定
// 请求格式 xml,
// httpConnection.setRequestProperty("Accept",
"application/json");// 设定响应的信息的格式为
httpConnection.setRequestProperty("Content-Type", "text/xml");
// json,也可以设定xml格式的
httpConnection.setRequestProperty("Charset", "utf-8");
// //特定http服务器需要的信息,根据服务器所需要求添加
httpConnection.connect();
JSONObject jdata = new JSONObject();
for (String Key : data.keySet()) {
jdata.element(Key, data.get(Key));
}
DataOutputStream out = new DataOutputStream(
httpConnection.getOutputStream());
System.out.println("out"+httpConnection.getOutputStream());
out.writeBytes(jdata.toString());
out.flush();
out.close();
// 读取响应
BufferedReader reader = new
BufferedReader(new InputStreamReader(
httpConnection.getInputStream(),"utf-8"));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes());
sb.append(lines);
}
reader.close();
httpConnection.disconnect();
obj = JSON.parse(sb.toString().getBytes("utf8"));
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
前期仿照http://bbs.csdn.net/topics/390417769?page=1;方法修改的,大家也可以参考一下