下面列出了怎么用org.apache.http.impl.client.SystemDefaultHttpClient的API类实例代码及写法,或者点击链接到github查看源代码。
private SystemDefaultHttpClient getHttpClient() {
final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY, use_jaas_creds);
return httpClient;
}
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
SystemDefaultHttpClient httpClient = getHttpClient();
doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));
// Always do a GET before POST to trigger the SPNego negotiation
if (doPost) {
HttpPost post = new HttpPost(getBaseURL());
byte [] postBytes = POST.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);
// Important that the entity is not repeatable -- this means if
// we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
// the test will fail.
Assert.assertFalse(entity.isRepeatable());
post.setEntity(entity);
doHttpClientRequest(httpClient, post);
}
} finally {
stop();
}
}
private SystemDefaultHttpClient getHttpClient() {
final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY, use_jaas_creds);
return httpClient;
}
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
SystemDefaultHttpClient httpClient = getHttpClient();
doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));
// Always do a GET before POST to trigger the SPNego negotiation
if (doPost) {
HttpPost post = new HttpPost(getBaseURL());
byte [] postBytes = POST.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);
// Important that the entity is not repeatable -- this means if
// we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
// the test will fail.
Assert.assertFalse(entity.isRepeatable());
post.setEntity(entity);
doHttpClientRequest(httpClient, post);
}
} finally {
stop();
}
}
private SystemDefaultHttpClient getHttpClient() {
final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient();
httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true));
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpClient.getCredentialsProvider().setCredentials(
AuthScope.ANY, use_jaas_creds);
return httpClient;
}
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
SystemDefaultHttpClient httpClient = getHttpClient();
doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));
// Always do a GET before POST to trigger the SPNego negotiation
if (doPost) {
HttpPost post = new HttpPost(getBaseURL());
byte[] postBytes = POST.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);
// Important that the entity is not repeatable -- this means if
// we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
// the test will fail.
Assert.assertFalse(entity.isRepeatable());
post.setEntity(entity);
doHttpClientRequest(httpClient, post);
}
} finally {
stop();
}
}
public static void publish(String url, String username, String password, String testCaseFolderName, String dataFileName) {
log.info("Starting WSO2 HttpEventPublisher Client");
KeyStoreUtil.setTrustStoreParams();
HttpClient httpClient = new SystemDefaultHttpClient();
try {
HttpPost method = new HttpPost(url);
List<String> messagesList = readMsg(getTestDataFileLocation(testCaseFolderName, dataFileName));
for (String message : messagesList) {
StringEntity entity = new StringEntity(message);
log.info("Sending message:");
log.info(message + "\n");
method.setEntity(entity);
if (url.startsWith("https")) {
processAuthentication(method, username, password);
}
httpClient.execute(method).getEntity().getContent().close();
Thread.sleep(1000);
}
Thread.sleep(500); // Waiting time for the message to be sent
} catch (Throwable t) {
log.error("Error when sending the messages", t);
}
}
public static void main(String[] args) {
HttpClient client1 = new DefaultHttpClient(); // BAD
HttpClient client2 = new SystemDefaultHttpClient(); // OK
try {
SSLContext context1 = SSLContext.getInstance("SSL"); // BAD
SSLContext context2 = SSLContext.getInstance("TLS"); // OK
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
log.info("Starting WSO2 Http Client");
HttpUtil.setTrustStoreParams();
String url = args[0];
String username = args[1];
String password = args[2];
String sampleNumber = args[3];
String filePath = args[4];
HttpClient httpClient = new SystemDefaultHttpClient();
try {
HttpPost method = new HttpPost(url);
filePath = HttpUtil.getMessageFilePath(sampleNumber, filePath, url);
readMsg(filePath);
for (String message : messagesList) {
StringEntity entity = new StringEntity(message);
log.info("Sending message:");
log.info(message + "\n");
method.setEntity(entity);
if (url.startsWith("https")) {
processAuthentication(method, username, password);
}
httpClient.execute(method).getEntity().getContent().close();
}
Thread.sleep(500); // Waiting time for the message to be sent
} catch (Throwable t) {
log.error("Error when sending the messages", t);
}
}
@Override
public void run() {
HttpClient httpClient = new SystemDefaultHttpClient();
try {
HttpPost method = new HttpPost(url);
log.info("Sending messages..");
long lastTime = System.currentTimeMillis();
DecimalFormat decimalFormat = new DecimalFormat("#");
while (count < noOfEvents) {
count++;
String temp = "{\"event\": " + getRandomEvent(count).toString() + "}";
StringEntity entity = new StringEntity(temp);
method.setEntity(entity);
if (url.startsWith("https")) {
processAuthentication(method, username, password);
}
httpClient.execute(method).getEntity().getContent().close();
if (count % elapsedCount == 0) {
long currentTime = System.currentTimeMillis();
long elapsedTime = currentTime - lastTime;
double throughputPerSecond = (((double) elapsedCount) / elapsedTime) * 1000;
lastTime = currentTime;
log.info("Sent " + elapsedCount + " sensor events in " + elapsedTime +
" milliseconds with total throughput of " + decimalFormat.format(throughputPerSecond) +
" events per second.");
}
}
} catch (Throwable t) {
log.error("Error when sending the messages", t);
}
}
@Override
public boolean verifyIAMPassword(Entry user, String pw) throws LdapInvalidAttributeValueException, LdapAuthenticationException {
try {
LOG.debug("Verifying {} {} with accessKey <hidden> and secretKey <hidden>",
"user", user.get("uid").getString());
HttpClient client = new SystemDefaultHttpClient();
HttpPost post = new HttpPost("https://signin.aws.amazon.com/oauth");
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36");
post.setHeader("Referer", "https://signin.aws.amazon.com/oauth");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("client_id", "arn:aws:iam::015428540659:user/homepage"));
urlParameters.add(new BasicNameValuePair("isIAMUser", "1"));
urlParameters.add(new BasicNameValuePair("account", user.get("accountNumber").getString()));
urlParameters.add(new BasicNameValuePair("username", user.get("uid").getString()));
urlParameters.add(new BasicNameValuePair("password", pw));
urlParameters.add(new BasicNameValuePair("Action", "login"));
urlParameters.add(new BasicNameValuePair("redirect_uri", "https://console.aws.amazon.com/console/home?state=hashArgs%23&isauthcode=true"));
urlParameters.add(new BasicNameValuePair("forceMobileApp", ""));
urlParameters.add(new BasicNameValuePair("forceMobileLayout", ""));
urlParameters.add(new BasicNameValuePair("mfaLoginFailure", ""));
urlParameters.add(new BasicNameValuePair("RemainingExpiryPeriod", ""));
urlParameters.add(new BasicNameValuePair("mfacode", ""));
urlParameters.add(new BasicNameValuePair("next_mfacode", ""));
post.setEntity(new UrlEncodedFormEntity(urlParameters, Charset.forName("UTF-8")));
HttpResponse response = client.execute(post);
return containsHeaders(response, "aws-account-alias", "aws-creds");
} catch (IOException e) {
LOG.error("Exception validating password for " + user.get("uid").getString(), e);
return false;
} catch (RuntimeException t) {
LOG.error("Exception validating password for " + user.get("uid").getString(), t);
throw t;
}
}
public LayerHttpServiceImpl() {
// Create a HTTP client object, which will initiate the connection:
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
setClient(new SystemDefaultHttpClient(httpParams));
}
public HttpClient createHttpClient() {
return new SystemDefaultHttpClient();
}