公司用HttpURLConnection去调用第三方的接口,然后呢人家的编码格式是unicode格式的
而且还是http-get请求。我拿到的数据是utf-8的中文字符串。想问下大佬要怎么改。
谢谢谢谢!
https://blog.csdn.net/xiao_mink/article/details/53699773
你是java 吧,想转换下字符的编码吧,
如果以前是GBK可以转到UTF-8
变量str以前是GBK编码
byte[] data=str.getBytes("GBK");
String strUTF8=new String(data, ‘UTF-8");
这要就可以互相转换了,如果是直接想用
byte[] data=strUTF8.getBytes("UTF-8");
URL.openConnection()得到一个URLConnection对象,然后用URLConnection.setRequestProperty()来设置头信息
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
可以指定body的编码
out = new PrintWriter(conn.getOutputStream());
PrintWriter不能指定编码,只能使用参数中的流(Stream)中的编码,是什么就用什么
https://blog.csdn.net/u010113247/article/details/52439895
这个应该好处理,使得两边编码一致即可。对面服务器没法改,那就只要修改自己的的编码方式了哦。楼上介绍的都可以
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(false);//post请求改为TRUE
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
connection.setRequestProperty("Charset", "utf-8");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.connect();
if (connection.getResponseCode() == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
return result;
}
URLEncoder.encode(str,"UTF-8");