欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在传输的过程中,统一采用utf-8编码,为了取得汉字,所以流中采用utf-8编码

程序员文章站 2022-04-11 17:13:00
...
[size=medium]前两天由于dns接口有变动,我帮忙测试dns解析业务:
由于在传输的过程中涉及到乱码问题,所以在传输的过程中,统一采用utf-8编码。为了能正常显示汉字,所以我们在传输过程中,流也要采用utf-8编码:[/size]

public static String getPageContent(String url, String strPostRequest) {
String strUrl = url;
// 读取结果网页
StringBuffer buffer = new StringBuffer();
System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
System.setProperty("sun.net.client.defaultReadTimeout", "5000");
try {
URL newUrl = new URL(strUrl);
HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
// POST方式的额外数据
if (strPostRequest.length() > 0) {
hConnect.setDoOutput(true);
hConnect.setRequestMethod("POST");

OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream(),"utf-8");
out.write(strPostRequest);
out.flush();
out.close();
}
// 读取内容
BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream(),"utf-8"));
int ch;
for (int length = 0; (ch = rd.read()) > -1; length++)
buffer.append((char) ch);
rd.close();
hConnect.disconnect();
return buffer.toString().trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}



说明:以post方法访问url,传输过程中流采用utf-8编码。
相关标签: SUN .net