如何为HttpClient上的每个请求获取特定凭据? 问题我现在有第二个线程似乎取代以前的第一个线程凭据。
以下是我的示例代码:
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 :(得分:0)
如果您希望每个线程拥有单独的凭据,那么您还需要为每个线程设置一个单独的客户端 - 每个客户端都有一组凭据。
将GetThread的构造函数更改为
public GetThread(HttpConnectionManager connectionManager,String username,String password) {
this.httpClient = new HttpClient(connectionManager);
this.username= username;
this.password= password;
}
那应该做你需要的。