java urlconnection乱码_使用HttpURLConnection.getOutputStream时遇到中文乱码解决方法

同样是对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;方法修改的,大家也可以参考一下

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值