httpurlconnection 乱码
时间: 2023-08-27 09:20:19 浏览: 178
在使用HttpURLConnection发送POST请求时,如果请求参数中包含中文,且在后端显示出现乱码,可能是由于编码问题导致的。一种可能的原因是POST的form没有进行转码,服务器端将字节转换成utf8编码时,如果读取的字节不是3的倍数或只读取了部分字节,就会导致乱码。解决这个问题的方法是将获取服务器返回的输入流转换成utf-8格式的编码。可以通过在HttpURLConnection实例中将获取到的输入流写入BufferedReader时,指定编码为utf-8,代码如下:
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8")); //转成utf-8格式
StringBuilder response = new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
System.out.println(response.toString());
这样可以确保从服务器获取的数据以utf-8格式进行解码,避免乱码问题的发生。 [2][3<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [HttpURLConnection发起请求中文数据乱码问题解决](https://blog.csdn.net/Pandafz1997/article/details/126961680)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [HttpURLConnection获取数据中的中文乱码](https://blog.csdn.net/qq_39686941/article/details/128141347)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文