2012-05-14 285 views
3

我有一個客戶端通過https post將文件上傳到服務器。它使用代理,這是我的代碼apache httpclient + ntlm身份驗證

public void upload() throws Exception { 

    //create default client 
    DefaultHttpClient client = new DefaultHttpClient(); 

    //set proxy authentication if specified 
    if (proxy.equals("yes") && proxyAuth.equals("yes")){ 
    client.getCredentialsProvider().setCredentials(
      new AuthScope(address, port), 
      new UsernamePasswordCredentials(proxyUsername, proxyPassword)); 
    } 

    //set proxy if specified 
    if (proxy.equals("yes")){ 
     HttpHost proxy = new HttpHost(address, port); 
     client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); 
    } 

    HttpPost post = new HttpPost(url); 
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

    File dir = new File(inputFilePath); 
    File[] fileArray = dir.listFiles(); 
    File file = fileArray[0]; 

    FileBody uploadFilePart = new FileBody(file); 

    entity.addPart("file", uploadFilePart); 
    entity.addPart("username", new StringBody(username)); 
    entity.addPart("password", new StringBody(password)); 

    post.setEntity(entity); 

    //execute post and get response 
    String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); 

    client.getConnectionManager().shutdown(); 

    log4j.info(response); 

    if(!response.substring(0, 3).equalsIgnoreCase("200")){ 
     Exception e = new Exception("An error has occurred server side: "); 
     throw e; 
    } 
} 

現在的問題是這完美的作品有時有有時我得到下面的錯誤。

org.apache.http.impl.client.AbstractAuthenticationHandler.selectScheme(AbstractAuthenticationHandler.java:149) - 身份驗證方案NTLM不支持」

+0

你試過跟隨http://hc.apache.org/httpcomponents-client-ga/ntlm.html說明? – DanLebrero

+0

你試過了。但仍然是相同的問題 – user732362

+0

如果您使用httpclient 3,您可以使用此工具來簡化這種身份驗證情況https://github.com/DovAmir/httpclientAuthHelper –

回答

1

嘗試 - 取而代之的是: 新UsernamePasswordCredentials(在proxyUsername,對proxyPassword)

使用這樣的: 新NTCredentials(在proxyUsername,對proxyPassword, 「localhostname」, 「域」)