下面列出了org.apache.http.impl.client.SystemDefaultHttpClient#org.apache.http.auth.Credentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testUrlCredDefaultProvider() throws HTTPException {
String url = "https://" + username + ":" + password + "@" + host + "/something/garbage.grb?query";
logger.info("Testing {}", url);
try (HTTPMethod method = HTTPFactory.Get(url)) {
// we should have a default BasicCredentialProvider available, even though
// we didn't call the factory with a specific provider
HTTPSession session = method.getSession();
CredentialsProvider credentialsProvider = session.sessionprovider;
assertThat(credentialsProvider).isNotNull();
AuthScope expectedAuthScope = new AuthScope(host, 80);
Credentials credentials = credentialsProvider.getCredentials(expectedAuthScope);
assertThat(credentials).isNotNull();
assertThat(credentials.getUserPrincipal().getName()).isEqualTo(username);
assertThat(credentials.getPassword()).isEqualTo(password);
}
}
public void initServers() throws HTTPException {
if (serverNames == null) {
servers = new ArrayList<>(); // empty list
return;
}
this.servers = new ArrayList<>(this.serverNames.length);
for (String name : this.serverNames) {
HTTPSession session = HTTPFactory.newSession(name);
if (user != null && pass != null) {
Credentials bp = new UsernamePasswordCredentials(user, pass);
BasicCredentialsProvider bcp = new BasicCredentialsProvider();
bcp.setCredentials(AuthScope.ANY, bp);
session.setCredentialsProvider(bcp);
}
session.setUserAgent("TDM");
servers.add(new Server(name, session));
}
}
public static Credentials getCredentials( final String user,
final String password ) {
if ( StringUtils.isEmpty( user ) ) {
return null;
}
final int domainIdx = user.indexOf( DOMAIN_SEPARATOR );
if ( domainIdx == -1 ) {
return new UsernamePasswordCredentials( user, password );
}
try {
final String domain = user.substring( 0, domainIdx );
final String username = user.substring( domainIdx + 1 );
final String host = InetAddress.getLocalHost().getHostName();
return new NTCredentials( username, password, host, domain );
} catch ( UnknownHostException uhe ) {
return new UsernamePasswordCredentials( user, password );
}
}
private void doTest(boolean async) throws Exception {
setupClient(async);
assertEquals("Hello Alice", greeter.greetMe("Alice"));
assertEquals("Hello Bob", greeter.greetMe("Bob"));
try {
BindingProvider bp = (BindingProvider)greeter;
if (async) {
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("blah", "foo");
bp.getRequestContext().put(Credentials.class.getName(), creds);
} else {
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "blah");
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "foo");
}
greeter.greetMe("Alice");
fail("Password was wrong, should have failed");
} catch (WebServiceException wse) {
//ignore - expected
}
}
public static CloseableHttpResponse execute(HttpUriRequest req, @Nullable Credentials auth) throws IOException {
if (auth != null) {
URI uri = req.getURI();
AuthScope scope = new AuthScope(uri.getHost(), uri.getPort());
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(scope, auth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(provider);
return get().execute(req, context);
}
return execute(req);
}
public boolean add(Credentials credential) {
boolean exists = false;
for (CredentialsTableRow credentialData : credentialsTableData) {
UsernamePasswordCredentials savedCredential = (UsernamePasswordCredentials) credentialData.getCredentials();
String savedUsername = savedCredential.getUserPrincipal().getName();
String username = credential.getUserPrincipal().getName();
String savedPassword = savedCredential.getPassword();
String password = credential.getPassword();
if (savedUsername.contentEquals(username) && savedPassword.contentEquals(password)) {
exists = true;
break;
}
}
if (!exists) {
CredentialsTableRow credentialsTableRow = new CredentialsTableRow(credential, credentialsTableData.size());
credentialsTableData.add(credentialsTableRow);
int row = credentialsTableData.indexOf(credentialsTableRow);
fireTableRowsInserted(row, row);
return true;
}
return false;
}
private void outputProductsPageChanged() {
this.downloadRemoteProductsHelper.cancelDownloadingProductsQuickLookImage();
if (this.localRepositoryProductsThread == null) {
AbstractProductsRepositoryPanel selectedProductsRepositoryPanel = this.repositorySelectionPanel.getSelectedProductsRepositoryPanel();
if (selectedProductsRepositoryPanel instanceof RemoteProductsRepositoryPanel) {
OutputProductListModel productListModel = this.repositoryOutputProductListPanel.getProductListPanel().getProductListModel();
List<RepositoryProduct> productsWithoutQuickLookImage = productListModel.findProductsWithoutQuickLookImage();
if (productsWithoutQuickLookImage.size() > 0) {
if (logger.isLoggable(Level.FINE)) {
int currentPageNumber = selectedProductsRepositoryPanel.getOutputProductResults().getCurrentPageNumber();
String repositoryName = selectedProductsRepositoryPanel.getRepositoryName();
logger.log(Level.FINE, "Start downloading the quick look images for " + productsWithoutQuickLookImage.size()+" products from page number " + currentPageNumber + " using the '" +repositoryName+"' remote repository.");
}
RemoteProductsRepositoryPanel remoteProductsRepositoryPanel = (RemoteProductsRepositoryPanel)selectedProductsRepositoryPanel;
Credentials selectedCredentials = remoteProductsRepositoryPanel.getSelectedAccount();
RemoteProductsRepositoryProvider productsRepositoryProvider = remoteProductsRepositoryPanel.getProductsRepositoryProvider();
this.downloadRemoteProductsHelper.downloadProductsQuickLookImageAsync(productsWithoutQuickLookImage, productsRepositoryProvider, selectedCredentials, this.repositoryOutputProductListPanel);
}
}
}
}
@Override
public void process( final HttpRequest request, final HttpContext context )
throws HttpException, IOException
{
AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE );
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute( ClientContext.CREDS_PROVIDER );
HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST );
// If not auth scheme has been initialized yet
if( authState.getAuthScheme() == null )
{
AuthScope authScope = new AuthScope( targetHost.getHostName(),
targetHost.getPort() );
// Obtain credentials matching the target host
Credentials creds = credsProvider.getCredentials( authScope );
// If found, generate BasicScheme preemptively
if( creds != null )
{
authState.setAuthScheme( new BasicScheme() );
authState.setCredentials( creds );
}
}
}
public void downloadProductsQuickLookImageAsync(List<RepositoryProduct> productsWithoutQuickLookImage, RemoteProductsRepositoryProvider productsRepositoryProvider,
Credentials credentials, RepositoryOutputProductListPanel repositoryProductListPanel) {
createThreadPoolExecutorIfNeeded();
DownloadProductsQuickLookImageRunnable runnable = new DownloadProductsQuickLookImageRunnable(productsWithoutQuickLookImage, productsRepositoryProvider,
credentials, this.remoteRepositoriesSemaphore, repositoryProductListPanel) {
@Override
protected void finishRunning() {
super.finishRunning();
finishRunningDownloadProductsQuickLookImageThreadLater(this);
}
};
this.runningTasks.put(runnable, null);
this.threadPoolExecutor.execute(runnable); // start the thread
}
/**
* Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
*
* @param proxyUri Optional HTTP proxy URI to use with the transport.
* @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
* proxy.
* @return The resulting HttpTransport.
* @throws IOException If there is an issue connecting to Google's certification server.
* @throws GeneralSecurityException If there is a security issue with the keystore.
*/
public static ApacheHttpTransport createApacheHttpTransport(
@Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
throws IOException, GeneralSecurityException {
checkArgument(
proxyUri != null || proxyCredentials == null,
"if proxyUri is null than proxyCredentials should be null too");
ApacheHttpTransport transport =
new ApacheHttpTransport.Builder()
.trustCertificates(GoogleUtils.getCertificateTrustStore())
.setProxy(
proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
.build();
if (proxyCredentials != null) {
((DefaultHttpClient) transport.getHttpClient())
.getCredentialsProvider()
.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
}
return transport;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
Credentials creds;
if (authState.getAuthScheme() == null) {
AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
CredentialsProvider credsProvider =
(CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost =
(HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authScheme != null) {
creds =
credsProvider.getCredentials(new AuthScope(
targetHost.getHostName(),
targetHost.getPort()));
if (creds == null) {
throw new HttpException("No credentials for preemptive authentication");
}
authState.update(authScheme, creds);
}
}
}
public Response execute(final Request request) throws ArangoDBException, IOException {
final String url = buildUrl(buildBaseUrl(host), request);
final HttpRequestBase httpRequest = buildHttpRequestBase(request, url);
httpRequest.setHeader("User-Agent", "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)");
if (contentType == Protocol.HTTP_VPACK) {
httpRequest.setHeader("Accept", "application/x-velocypack");
}
addHeader(request, httpRequest);
final Credentials credentials = addCredentials(httpRequest);
if (LOGGER.isDebugEnabled()) {
CURLLogger.log(url, request, credentials, util);
}
Response response;
response = buildResponse(client.execute(httpRequest));
checkError(response);
return response;
}
public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException,
IllegalAccessException
{
CredentialsProvider provider = getCredentialsProvider();
String httpScheme = AuthScope.ANY_SCHEME;
if (authScheme == AuthScheme.BASIC) {
httpScheme = AuthSchemes.BASIC;
} else if (authScheme == AuthScheme.DIGEST) {
httpScheme = AuthSchemes.DIGEST;
}
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
Credentials credentials = provider.getCredentials(authScope);
Assert.assertNotNull("Credentials", credentials);
Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()));
UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials)credentials;
Assert.assertEquals("Username", username, pwdCredentials.getUserName());
Assert.assertEquals("Password", password, pwdCredentials.getPassword());
}
/**
* @return a generic REST client with authentication configured
*/
protected Client restClient() {
try {
final HttpClient httpClient = clientBuilder().build();
final Credentials credentials = credentials();
return restClientFactory
.create(RestClientConfiguration.DEFAULTS
.withHttpClient(() -> httpClient)
.withCustomizer(getObjectMapperCustomizer(testSuiteObjectMapperResolver))
)
.register(new BasicAuthentication(credentials.getUserPrincipal().getName(), credentials.getPassword()));
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testAddCredentials() throws IOException, ClassNotFoundException {
String testUser = "test_username";
slaveServer.setUsername( testUser );
String testPassword = "test_password";
slaveServer.setPassword( testPassword );
String host = "somehost";
slaveServer.setHostname( host );
int port = 1000;
slaveServer.setPort( "" + port );
HttpClientContext auth = slaveServer.getAuthContext();
Credentials cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
assertEquals( testUser, cred.getUserPrincipal().getName() );
assertEquals( testPassword, cred.getPassword() );
String user2 = "user2";
slaveServer.setUsername( user2 );
slaveServer.setPassword( "pass2" );
auth = slaveServer.getAuthContext();
cred = auth.getCredentialsProvider().getCredentials( new AuthScope( host, port ) );
assertEquals( user2, cred.getUserPrincipal().getName() );
}
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;
}
private Credentials getCredentials() {
if (StringUtil.isEmpty(getUsername())) {
throw new CrawlerSystemException("username is empty.");
}
if (Constants.NTLM.equals(getProtocolScheme())) {
final Map<String, String> parameterMap = ParameterUtil.parse(getParameters());
final String workstation = parameterMap.get("workstation");
final String domain = parameterMap.get("domain");
return new NTCredentials(getUsername(), getPassword(), workstation == null ? StringUtil.EMPTY : workstation,
domain == null ? StringUtil.EMPTY : domain);
}
return new UsernamePasswordCredentials(getUsername(), getPassword() == null ? StringUtil.EMPTY : getPassword());
}
public RemoteProductDownloader(RemoteProductsRepositoryProvider remoteProductsRepositoryProvider, RepositoryProduct productToDownload,
Path localRepositoryFolderPath, Credentials credentials) {
this.remoteProductsRepositoryProvider = remoteProductsRepositoryProvider;
this.productToDownload = productToDownload;
this.localRepositoryFolderPath = localRepositoryFolderPath;
this.credentials = credentials;
}
private static boolean isRepositoryChanged(RemoteRepositoryCredentials savedRepositoryCredentials, RemoteRepositoryCredentials repositoryCredentials) {
List<Credentials> credentials = repositoryCredentials.getCredentialsList();
if (credentials.size() != savedRepositoryCredentials.getCredentialsList().size()) {
// some credentials deleted or added = changed
return true;
}
for (Credentials credential : credentials) {
if (!savedRepositoryCredentials.credentialExists(credential)) {
return true; // the credential was not found = changed
}
}
return false;
}
public InputStream getStream(String baseUrl, RasterLayer layer) throws IOException {
String url = baseUrl;
HttpContext context = null;
if (layer instanceof ProxyLayerSupport) {
context = new BasicHttpContext();
// pass url and layer id to the CompositeInterceptor
context.setAttribute(CompositeInterceptor.BASE_URL, baseUrl);
context.setAttribute(CompositeInterceptor.LAYER_ID, layer.getId());
// handle proxy authentication and interceptors
ProxyLayerSupport proxyLayer = (ProxyLayerSupport) layer;
ProxyAuthentication authentication = proxyLayer.getProxyAuthentication();
url = addCredentialsToUrl(baseUrl, authentication);
// -- add basic authentication
if (null != authentication
&& (ProxyAuthenticationMethod.BASIC.equals(authentication.getMethod()) ||
ProxyAuthenticationMethod.DIGEST.equals(authentication.getMethod()))) {
// Set up the credentials:
Credentials creds = new UsernamePasswordCredentials(authentication.getUser(),
authentication.getPassword());
URL u = new URL(url);
AuthScope scope = new AuthScope(u.getHost(), u.getPort(), authentication.getRealm());
// thread-safe, this is ok
client.getCredentialsProvider().setCredentials(scope, creds);
}
}
// Create the GET method with the correct URL:
HttpGet get = new HttpGet(url);
// Execute the GET:
HttpResponse response = client.execute(get, context);
log.debug("Response: {} - {}", response.getStatusLine().getStatusCode(), response.getStatusLine()
.getReasonPhrase());
return response.getEntity().getContent();
}
/**
* Create an {@link HttpTransport} based on an type class and an optional HTTP proxy.
*
* @param type The type of HttpTransport to use.
* @param proxyAddress The HTTP proxy to use with the transport. Of the form hostname:port. If
* empty no proxy will be used.
* @param proxyUsername The HTTP proxy username to use with the transport. If empty no proxy
* username will be used.
* @param proxyPassword The HTTP proxy password to use with the transport. If empty no proxy
* password will be used.
* @return The resulting HttpTransport.
* @throws IllegalArgumentException If the proxy address is invalid.
* @throws IOException If there is an issue connecting to Google's Certification server.
*/
public static HttpTransport createHttpTransport(
HttpTransportType type,
@Nullable String proxyAddress,
@Nullable RedactedString proxyUsername,
@Nullable RedactedString proxyPassword)
throws IOException {
logger.atFine().log(
"createHttpTransport(%s, %s, %s, %s)", type, proxyAddress, proxyUsername, proxyPassword);
checkArgument(
proxyAddress != null || (proxyUsername == null && proxyPassword == null),
"if proxyAddress is null then proxyUsername and proxyPassword should be null too");
checkArgument(
(proxyUsername == null) == (proxyPassword == null),
"both proxyUsername and proxyPassword should be null or not null together");
URI proxyUri = parseProxyAddress(proxyAddress);
try {
switch (type) {
case APACHE:
Credentials proxyCredentials =
proxyUsername != null
? new UsernamePasswordCredentials(proxyUsername.value(), proxyPassword.value())
: null;
return createApacheHttpTransport(proxyUri, proxyCredentials);
case JAVA_NET:
PasswordAuthentication proxyAuth =
proxyUsername != null
? new PasswordAuthentication(
proxyUsername.value(), proxyPassword.value().toCharArray())
: null;
return createNetHttpTransport(proxyUri, proxyAuth);
default:
throw new IllegalArgumentException(
String.format("Invalid HttpTransport type '%s'", type.name()));
}
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
}
@Test
public void createNtlmCredentialsProvider() {
CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.NTLM);
Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80));
assertThat(credentials, instanceOf(NTCredentials.class));
NTCredentials ntCredentials = (NTCredentials) credentials;
assertEquals("DOMAIN", ntCredentials.getDomain());
assertEquals("HOST", ntCredentials.getWorkstation());
assertEquals("pass", ntCredentials.getPassword());
Credentials proxyCredentials = credentialsProvider.getCredentials(new AuthScope("proxy", 8080));
assertThat(proxyCredentials, instanceOf(UsernamePasswordCredentials.class));
UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) proxyCredentials;
assertEquals("proxyUsername", userCredentials.getUserName());
}
@Test
public void testHttpDownloadWithAuthenticationAndSsl() throws Exception {
Credentials auth = HttpService.basic("testuser", "testpasswd");
String output = HttpService.contentAsString("https://httpbin.org/basic-auth/testuser/testpasswd", auth);
System.out.println("downloaded size: " + output.length());
System.out.println("downloaded content: " + output);
Assert.assertTrue("download did not work correctly", output != null && output.length() > 16);
}
private static Credentials createCredentials(final String username, final String password) {
final String user;
final String domain;
int backslashIndex = username.indexOf('\\');
if (backslashIndex >= 0) {
user = username.substring(backslashIndex + 1);
domain = username.substring(0, backslashIndex);
} else {
user = username;
domain = System.getProperty("http.auth.ntlm.domain", "");
}
return new NTCredentials(user, password, HostUtil.getLocalHostName(), domain);
}
public static void log(
final String url,
final Request request,
final Credentials credencials,
final ArangoSerialization util) {
final RequestType requestType = request.getRequestType();
final boolean includeBody = (requestType == RequestType.POST || requestType == RequestType.PUT
|| requestType == RequestType.PATCH || requestType == RequestType.DELETE) && request.getBody() != null;
final StringBuilder buffer = new StringBuilder();
if (includeBody) {
buffer.append("\n");
buffer.append("cat <<-___EOB___ | ");
}
buffer.append("curl -X ").append(requestType);
buffer.append(" --dump -");
if (request.getHeaderParam().size() > 0) {
for (final Entry<String, String> header : request.getHeaderParam().entrySet()) {
buffer.append(" -H '").append(header.getKey()).append(":").append(header.getValue()).append("'");
}
}
if (credencials != null) {
buffer.append(" -u ").append(credencials.getUserPrincipal().getName()).append(":")
.append(credencials.getPassword());
}
if (includeBody) {
buffer.append(" -d @-");
}
buffer.append(" '").append(url).append("'");
if (includeBody) {
buffer.append("\n");
buffer.append((String) util.deserialize(request.getBody(), String.class));
buffer.append("\n");
buffer.append("___EOB___");
}
LOGGER.debug("[CURL] {}", buffer);
}
private HttpClient createHttpClient(){
CredentialsProvider credsProvider = new BasicCredentialsProvider();
if(user !=null && pwd !=null){
Credentials credentials = new UsernamePasswordCredentials(user, pwd);
credsProvider.setCredentials(AuthScope.ANY, credentials);
}
HttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.build();
return httpclient;
}
/**
* Returns the NTCredentials or UsernamePasswordCredentials object
*
* @param type
* @param authenticationInfo
* @return
*/
public static Credentials getCredentials(final ServerContext.Type type, final AuthenticationInfo authenticationInfo) {
if (type == ServerContext.Type.TFS) {
return getNTCredentials(authenticationInfo.getUserName(), authenticationInfo.getPassword());
} else {
return new UsernamePasswordCredentials(authenticationInfo.getUserName(), authenticationInfo.getPassword());
}
}
public static HttpsDispatcher getInstance(String uri, Credentials credentials) {
HttpsDispatcher dispatcher = new HttpsDispatcher(new HttpHost(uri),
new BasicHttpContext());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(dispatcher.host.getHostName(), dispatcher.host.getPort());
credsProvider.setCredentials(authScope, credentials);
((AbstractHttpClient) dispatcher.client).getCredentialsProvider().setCredentials(
authScope, credentials);
return dispatcher;
}
@Test
public void testSendExportOk() throws Exception {
slaveServer.setUsername( "uname" );
slaveServer.setPassword( "passw" );
slaveServer.setHostname( "hname" );
slaveServer.setPort( "1111" );
HttpPost httpPostMock = mock( HttpPost.class );
URI uriMock = new URI( "fake" );
final String responseContent = "baah";
when( httpPostMock.getURI() ).thenReturn( uriMock );
doReturn( uriMock ).when( httpPostMock ).getURI();
HttpClient client = mock( HttpClient.class );
when( client.execute( any(), any( HttpContext.class ) ) ).then( new Answer<HttpResponse>() {
@Override
public HttpResponse answer( InvocationOnMock invocation ) throws Throwable {
HttpClientContext context = invocation.getArgumentAt( 1, HttpClientContext.class );
Credentials cred = context.getCredentialsProvider().getCredentials( new AuthScope( "hname", 1111 ) );
assertEquals( "uname", cred.getUserPrincipal().getName() );
return mockResponse( 200, responseContent );
}
} );
// override init
when( slaveServer.getHttpClient() ).thenReturn( client );
when( slaveServer.getResponseBodyAsString( any() ) ).thenCallRealMethod();
doReturn( httpPostMock ).when( slaveServer ).buildSendExportMethod( anyString(), anyString(), any(
InputStream.class ) );
File tempFile;
tempFile = File.createTempFile( "PDI-", "tmp" );
tempFile.deleteOnExit();
String result = slaveServer.sendExport( tempFile.getAbsolutePath(), null, null );
assertEquals( responseContent, result );
}
public static void upload(URI uri, Credentials auth, File src, String description) throws IOException {
String cred = auth.getUserPrincipal().getName()+":"+auth.getPassword();
String encoding = Base64.encodeBase64String(cred.getBytes());
HttpPost httppost = new HttpPost(uri);
// Add in authentication
httppost.setHeader("Authorization", "Basic " + encoding);
FileBody data = new FileBody(src);
StringBody text = new StringBody(description, ContentType.TEXT_PLAIN);
// Build up multi-part form
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("upload", data)
.addPart("comment", text)
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.build();
httppost.setEntity(reqEntity);
// Execute post and get response
CloseableHttpClient client = get();
CloseableHttpResponse response = client.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
response.close();
}
}