// 设置身份验证凭据 String username = "SHLT"; String password = "91SN4Qq9"; String auth = username + ":" + password; byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes()); String authHeaderValue = "Basic " + new String(encodedAuth); // 设置连接到API端点 String endpoint = "http://dataservice.rjh.com.cn:9002/api/data?methodname=车辆管理"; URL url = new URL(endpoint); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", authHeaderValue); // 读取API端点的响应 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String s = response.toString(); System.out.println(s);优化以下这段代码,让response转成utf-8
时间: 2024-04-04 20:31:45 浏览: 58
以下是优化后的代码:
```java
String username = "SHLT";
String password = "91SN4Qq9";
String auth = username + ":" + password;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes());
String authHeaderValue = "Basic " + new String(encodedAuth);
String endpoint = "http://dataservice.rjh.com.cn:9002/api/data?methodname=车辆管理";
URL url = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", authHeaderValue);
InputStream inputStream = new BufferedInputStream(connection.getInputStream());
String encoding = "UTF-8"; // 指定返回结果的编码方式
String s = IOUtils.toString(inputStream, encoding); // 使用第三方库Apache Commons IO将InputStream转换成字符串
System.out.println(s);
```
主要的优化点是使用了第三方库Apache Commons IO来将`InputStream`转换成字符串,并指定了使用UTF-8编码进行转换。这样就可以确保响应结果被正确地转换成了UTF-8编码的字符串。
阅读全文