httpurlconnection 返回乱码
时间: 2023-10-28 13:24:36 浏览: 188
处理url乱码问题
当使用HttpURLConnection获取数据时,可能会出现返回乱码的情况。这通常是由于编码格式不一致造成的。默认情况下,Java中的HttpURLConnection使用的是UTF-8编码格式来获取数据。而如果你在解析返回数据时使用了其他编码格式,就可能会导致乱码的问题。
解决这个问题的方法是将获取到的输入流转换为相应的编码格式。例如,如果你希望以UTF-8格式解析数据,可以在获取输入流后将其转换为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编码格式解析,避免了返回乱码的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [HttpURLConnection中的乱码问题](https://blog.csdn.net/chenkaibsw/article/details/80197998)[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^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文