2017-09-12 48 views
-1

我遇到HttpUrlConnection问题。HttpUrlConnection'未授权'或'已连接'

我想从互联网上下载文件。
它第一次完美运作。
但是,当我再次尝试,我有一个异常,我已经“已连接”,或“正在连接”。

Exception in thread "main" java.lang.IllegalStateException: connect in 
progress 

我用Google搜索,发现我需要删除像con.setDoOutput(true);一些事情。 我做到了,并重新启动我的程序。 现在我又有了一个例外:401 unauthorized

我不明白该怎么做。 我的代码:

public boolean creerSession(String endpoint) throws IOException, JSONException, InterruptedException { 
    // Ouverture de la connexion 
    String url = new StringBuilder(endpoint).append("/auth").toString(); 
    URL obj = new URL(url); 
    validerAll(); 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

    // Définition des Request header 
    String urlParameters = new StringBuilder("username=").append(this.login).append("&password=").append(this.password).toString();   
    con.setRequestMethod("POST"); 
    con.getRequestMethod(); 

    // Envoi de la requete en POST 
    con.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.writeBytes(urlParameters); 
    wr.flush(); 
    wr.close(); 

任何想法?

+0

一旦你完成了'HttpURLConnection con'对象,你使用'disconnect()'吗?然后,你必须通过再次调用'(HttpURLConnection)obj.openConnection()'来创建一个新的实例,每个请求 –

+1

请在你的问题中包括两个例外的堆栈跟踪。 – EJP

+0

“401未授权”我想象的是您从网络服务获得的回复,表明您的请求未经授权。问题很可能是你如何尝试获得授权,如错误/缺少用户/密码组合 – Quintium

回答

0

@Emanuele Giona你是对的,断开连接()失踪,但即使我尝试了这一点,错误如下。 @Quitium这就是我解释道:如果我取消我的代码

con.setRequestMethod("POST"); 
con.getRequestMethod(); 
con.setDoOutput(true); 

我有一个未经授权的异常

堆栈跟踪(第一次它的确定,几分钟后,与正在连接的问题回来...)

Connected to the target VM, address: '127.0.0.1:61323', transport: 'socket' ticket de la session : XIZZAxWt36k0+lrEiVDKO6ijKitlwdwL1kx1EG1tiGGV3fJ3gw/In9zkBhTRjuTVWupmAh3xPQ1jRkByj50uRl0sn1vDdzE+gRiNHFIiF4TOmBQXwSkIPA== Exception in thread "main" java.lang.IllegalStateException: connect in progress at sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(HttpURLConnection.java:517) at sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:374) at GedWSTesting.downloadFile(GedWSTesting.java:60) at GedWSTesting.main(GedWSTesting.java:32) Disconnected from the target VM, address: '127.0.0.1:61323', transport: 'socket'

Process finished with exit code 1

我的代码(线57→64)

// open the connection 
    HttpURLConnection con = (HttpURLConnection) downloadUrl.openConnection(); 
    con.setRequestProperty("Cookie", "LLCookie=" + mainSession.getTicket() + "; path=/livelink/; secure"); 
    con.setRequestMethod("HEAD"); 
    con.setInstanceFollowRedirects(false); 
    con.setReadTimeout(50000); 
    con.setConnectTimeout(10000); 
    con.connect(); 
+0

嗨,很抱歉,这么晚回答。问题是disconnect()。 – Quezac

相关问题