2013-01-08 25 views
0

URL我想下面的代碼:後處理文件使用Java身份驗證

public class URLUploader { 

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

     URL url = new URL("http://77.203.65.164:6011"); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 

     String name = "user"; 
       String password = "password"; 

       String authString = name + ":" + password; 
       System.out.println("auth string: " + authString); 
       byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); 
       String authStringEnc = new String(authEncBytes); 
       System.out.println("Base64 encoded auth string: " + authStringEnc); 

     conn.setRequestProperty("Authorization", "Basic " + authStringEnc); 
     OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); 

     writer.write("/var/www/html/kannel/javacode/13569595024298.xml"); 
     writer.flush(); 
     String line; 
     BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
     while ((line = reader.readLine()) != null) { 
      System.out.println(line); 
     } 

     writer.close(); 
     reader.close(); 
    } 
} 

但我得到了以下錯誤:

auth string: optiweb:optiweb 
Base64 encoded auth string: b3B0aXdlYjpvcHRpd2Vi 
    Exception in thread "main" java.io.IOException: Server returned HTTP response code: 500 for URL: 77.203.65.164:6011 
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1403) 
    at URLUploader.main(URLUploader.java:32) 

出了什麼問題?

+0

您確定您收到驗證錯誤嗎?看起來好像你只是直接向遠程服務器寫入文件,但你可能想要將它作爲表單編碼數據發佈。對於初學者,我建議你使用jakarta [http client library](http://hc.apache.org/httpcomponents-client-ga/index.html)來處理這個問題。 – Zeki

回答

0

首先,HTTP響應碼500是「內部服務器錯誤」,並且與認證無關。

二,聲明

writer.write("/var/www/html/kannel/javacode/13569595024298.xml"); 

只是寫文件的完整路徑到服務器,而不是實際的文件內容,甚至沒有一個結尾的新行。這當然不是服務器期望的,也可能是500響應的原因。您正在構建和發送的請求也可能有其他問題,但如果沒有關於連接另一端的詳細API參考,則很難提供進一步的幫助。

+0

我試圖將文件寫入字節數組,但這不起作用,該數據類型是write.write()期待? –