2017-09-12 63 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

相關問題