public static String getHtmlCode(String path) { String result = null; try { HttpClient httpclient = getHttpClient(); HttpGet get = new HttpGet(path); HttpResponse response = httpclient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8")); String line; result = ""; while ((line = br.readLine()) != null) { result += line + "\n"; } } } catch(ConnectTimeoutException e) { System.out.println("ConnectTimeoutException timeout"); return null; } catch (SocketTimeoutException e) { System.out.println("SocketTimeoutException timeout"); return null; } catch (Exception e) { System.out.println(e.getMessage() + ":" + e.toString()); return null; } return result; } }我哪里错了?修改结果
时间: 2024-02-10 12:09:51 浏览: 91
这段代码也是使用的过时的HTTPClient,同样可能会导致编译错误。你可以使用OkHttp来实现相同的功能,如下所示:
```
public static String getHtmlCode(String path) {
String result = null;
OkHttpClient client = getHttpClient();
try {
Request request = new Request.Builder()
.url(path)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
result = response.body().string();
}
} catch (ConnectTimeoutException e) {
System.out.println("ConnectTimeoutException timeout");
return null;
} catch (SocketTimeoutException e) {
System.out.println("SocketTimeoutException timeout");
return null;
} catch (Exception e) {
System.out.println(e.getMessage() + ":" + e.toString());
return null;
}
return result;
}
```
这个代码使用OkHttp的Request和Response对象来获取HTML代码,并且也支持设置连接和读取超时时间。使用OkHttp可以更加方便地实现HTTP请求,同时也支持HTTP/2和HTTP/1.1协议。
阅读全文