2

I am trying to read a git file by providing a http url of git repository. My repository is not public so I provided the authentication details in my code and tried to connect but it is giving errors. My code is as given below:

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";
        }
    }
}

But I am getting the IllegalStateException error on running this code. The full error stack is as given below: Exception in thread "main" java.lang.IllegalStateException: Already connected at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3014) What can be the reason for this error and how to get it resolved?

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
Rain
  • 41
  • 7
  • Possible duplicate of ["Illegal State Exception: Already Connected" when using HttpURLConnection](https://stackoverflow.com/questions/29906562/illegal-state-exception-already-connected-when-using-httpurlconnection) – tomerpacific Dec 21 '18 at 07:38
  • it didn't worked for me – Rain Dec 21 '18 at 09:25
  • call this line **Map> searchHeader = searchHttp.getHeaderFields();** after this line **searchHttp.setRequestProperty("Authorization", basicAuth);** – Ramesh Subramanian Dec 21 '18 at 10:24
  • I tried but I got another error:Exception in thread "main" java.net.ConnectException: Connection timed out: connect at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at – Rain Dec 21 '18 at 11:36

1 Answers1

0

From the 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() is one of those methods that will implicitly call connect(). So you need to make sure to call it after the last call to setRequestProperty(). Or just remove that line.

Unrelated note: you're missing a space after Basic.

rustyx
  • 80,671
  • 25
  • 200
  • 267
  • If I remove getHeaderFields(), I get another error: Exception in thread "main" java.net.ConnectException: Connection timed out: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) – Rain Dec 21 '18 at 09:28
  • Well that's a whole other issue, probably a firewall issue or the port 8081 is wrong. – rustyx Dec 21 '18 at 10:40