IllegalStateException:已连接到HttpURL时已连接

时间:2018-12-21 07:26:45

标签: java exception httpurlconnection illegalstateexception

我正在尝试通过提供git存储库的http网址来读取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错误。完整的错误堆栈如下所示:     线程“主”中的异常java.lang.IllegalStateException:已连接         在sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3014) 该错误的原因是什么?如何解决?

1 个答案:

答案 0 :(得分:0)

来自javadoc

  

URLConnection对象经历两个阶段:首先创建它们,然后将它们连接起来。在创建之后和连接之前,可以指定各种选项(例如doInput和UseCaches)。连接后,尝试设置它们是错误的。必要时,依赖于连接的操作(如getContentLength)将隐式执行连接。

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

不相关的注释:您在Basic之后缺少空格。