2011-03-10 40 views
2

我已經編寫了以下java代碼以便從使用http基本身份驗證的服務器下載文件。但我得到HTTP 401錯誤。 然而,我可以通過直接從瀏覽器中點擊網址來下載文件。從我的java代碼中使用基本http身份驗證的服務器下載文件的問題

OutputStream out = null; 
    InputStream in = null; 
    URLConnection conn = null; 

    try { 
        // Get the URL 
         URL url = new URL("http://username:[email protected]/protected-area/somefile.doc"); 
        // Open an output stream for the destination file locally 
        out = new BufferedOutputStream(new FileOutputStream("file.doc")); 
        conn = url.openConnection(); 
        in = conn.getInputStream(); 

        // Get the data 
        byte[] buffer = new byte[1024]; 
        int numRead; 
        while ((numRead = in.read(buffer)) != -1) { 
         out.write(buffer, 0, numRead); 
        }    

    } catch (Exception exception) { 
        exception.printStackTrace(); 
    } 

但是,即時得到以下異常:當運行程序:

java.io.IOException: Server returned HTTP response code: 401 for URL: http://username:[email protected]/protected-area/somefile.doc 
     at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436) 
     at TestDownload.main(TestDownload.java:17) 

不過,我可以通過點擊網址,http://username:[email protected]/protected-area/somefile.doc從瀏覽器下載文件,直接。

什麼可能導致這個問題,以及以任何方式解決它?請致電 謝謝。

回答

2

我使用org.apache.http:

private StringBuffer readFromServer(String url) { 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 

    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { 
     public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { 
      AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); 

      if (authState.getAuthScheme() == null) { 
       Credentials credentials = new UsernamePasswordCredentials(
         Constants.SERVER_USERNAME, 
         Constants.SERVER_PASSWORD); 

       authState.setAuthScheme(new BasicScheme()); 
       authState.setAuthScope(AuthScope.ANY); 
       authState.setCredentials(credentials); 
      } 
     }  
    }; 

    httpclient.addRequestInterceptor(preemptiveAuth, 0); 

    HttpGet httpget = new HttpGet(url); 
    HttpResponse response; 

    InputStream instream = null; 
    StringBuffer result = new StringBuffer(); 

    try { 
     response = httpclient.execute(httpget); 

等等

相關問題