gpt4 book ai didi

java - Java中的可选方法参数

转载 作者:行者123 更新时间:2023-11-30 06:58:49 26 4
gpt4 key购买 nike

我有这个调用 http() 的函数 httpGet():

public static int httpGet(String url, StringBuilder response) throws IOException {
return http(url,(http)->http.setRequestMethod("GET"), response);
}

private static int http(String url, httpMethod method, StringBuilder response) throws IOException {
HttpURLConnection http = (HttpURLConnection)new URL(url).openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(5000);
method.doMethod(http);
int status = 404;
......
......
return status;
}

我想为 readTimeout 添加一个附加参数,该参数必须是可选的,并带有默认值,否则将使用该参数。

在这种情况下,所有调用的 readTimeout 都设置为 5000,但我希望执行此特定调用的超时时间更长。

我想我需要这个新参数是可选的,因为我不想更改调用此 http() 方法的实现。

我是这样调用它的:

Assert.assertEquals(HTTP_OK, httpGet(DEFAULT_BROWSCAP_ENDPOINT, result));

如何为 readTimeout 实现一个新的可选参数?

最佳答案

Java 没有像 Python、C++、VBA、Delphi 和许多语言那样的默认值。使用备用签名创建新的构造函数。

public static int httpGet(String url, StringBuilder response) throws IOException {
return httpGet(URL, response, 5000)
}

public static int httpGet(String url, StringBuilder response, int readTimeout) throws IOException {
return http(url,(http)->http.setRequestMethod("GET"), response, readTimeout);
}


private static int http(String url, httpMethod method, StringBuilder response) throws IOException {
return http(url, method, response, 5000);
}

private static int http(String url, httpMethod method, StringBuilder response, int readTimeout) throws IOException {
HttpURLConnection http = (HttpURLConnection)new URL(url).openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(readTimeout;
method.doMethod(http);
int status = 404;
......
......
return status;
}

关于java - Java中的可选方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com