2011-10-17 24 views
0

如何爲HttpClient上的每個請求擁有特定的憑據? 問題我現在有第二個線程似乎取代之前的第一個線程憑證。Apache HttpClient 3,爲每個請求使用不同憑據的多線程?

下面是我的示例代碼:

class GetThread extends Thread { 
    HttpClient httpClient; 

    private String username,password; 

    public GetThread(HttpClient httpClient,String username,String password) { 
     this.httpClient = httpClient; 
     this.username= username; 
     this.password= password; 
    } 

    public void run() { 

     Credentials defaultcreds = new UsernamePasswordCredentials(username, password); 
     httpClient.getState().setCredentials(new AuthScope("dummyhost", 80, AuthScope.ANY_REALM), defaultcreds); 
     HttpMethod method = new GetMethod("http://dummyhost/RSL/servlets/dv.data"); 

     method.setDoAuthentication(true); 
     try { 
      httpClient.executeMethod(method); 

      byte[] responseBody = method.getResponseBody(); 
      System.out.println(Thread.currentThread().getName()+" "+username+" "+new String(responseBody)); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     finally { 
      method.releaseConnection(); 
     } 

    } 
} 

而這就是我把我的主類中:

MultiThreadedHttpConnectionManager connectionManager = 
     new MultiThreadedHttpConnectionManager(); 

    HttpClient httpClient = new HttpClient(connectionManager); 
    GetThread getThread[] = {new GetThread(httpClient, "rsbatch1", "test1234"), 
      new GetThread(httpClient, "rsbatch12", "test1234")}; 

    for(int i=0;i<getThread.length;i++) 
    { 
     getThread[i].start(); 
    } 

回答

0

如果你想有每個線程獨立的憑證,那麼你需要有每個線程還有一個單獨的客戶端 - 每個客戶端都有一組憑據。

爲GetThread的構造器更改爲

public GetThread(HttpConnectionManager connectionManager,String username,String password) { 
    this.httpClient = new HttpClient(connectionManager); 
    this.username= username; 
    this.password= password; 
} 

而且應該做你所需要的。

相關問題