gpt4 book ai didi

java - 非法状态异常 : Already Connected while connecting to a HttpURL

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:47 24 4
gpt4 key购买 nike

我试图通过提供 git 存储库的 http url 来读取 git 文件。我的存储库不是公开的,因此我在代码中提供了身份验证详细信息并尝试连接,但出现错误。我的代码如下:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import com.sun.xml.internal.messaging.saaj.util.Base64;

public class testInAction {

static String username = "user@db.com";
static String password = "12345678";

public static void main(String[] args) throws Throwable {

String link = "https://stash.gto.intranet.db.com:8081/projects/myproject/browse";
URL searchURL = new URL(link);
System.out.println("start");
URLConnection searchHttp = (HttpURLConnection) searchURL.openConnection();
searchHttp.setRequestProperty("X-Requested-With", "Curl");
Map<String, List<String>> searchHeader = searchHttp.getHeaderFields();
String userPass = username + ":" + password;
String basicAuth = "Basic" + new String(new Base64().encode(userPass.getBytes()));
searchHttp.setRequestProperty("Authorization", basicAuth);
InputStream searchStream = searchHttp.getInputStream();
String searchResponse = searchGetStringFromStream(searchStream);
System.out.println(searchResponse);
}

private static String searchGetStringFromStream(InputStream seachStream1) throws IOException {
if (seachStream1 != null) {
Writer searchWriter = new StringWriter();
char[] searchBuffer = new char[2048];
try {
Reader searchReader = new BufferedReader(new InputStreamReader(seachStream1, "UTF-8"));
int counter;
while ((counter = searchReader.read(searchBuffer)) != -1) {
searchWriter.write(searchBuffer, 0, counter);
}
} finally {
seachStream1.close();
}
return searchWriter.toString();
} else {
return "No Contents";
}
}
}

但是我在运行此代码时收到 IllegalStateException 错误。完整的错误堆栈如下所示: 线程“main”中的异常 java.lang.IllegalStateException:已连接 在 sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3014)此错误的原因是什么?如何解决?

最佳答案

来自javadoc :

URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified (e.g., doInput and UseCaches). After connecting, it is an error to try to set them. Operations that depend on being connected, like getContentLength, will implicitly perform the connection, if necessary.

getHeaderFields() 是隐式调用 connect() 的方法之一。因此,您需要确保在最后一次调用 setRequestProperty() 之后调用它。或者只是删除该行。

不相关的注释:Basic 后面缺少一个空格。

关于java - 非法状态异常 : Already Connected while connecting to a HttpURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53880763/

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