org.hisp.dhis.util.HttpUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dhis2-java-client Show documentation
Show all versions of dhis2-java-client Show documentation
DHIS 2 API client for Java.
package org.hisp.dhis.util;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.net.URIBuilder;
import org.hisp.dhis.Dhis2Config;
public class HttpUtils
{
/**
* Returns a basic authentication string which is generated by prepending
* "Basic " and Base64-encoding username:password.
*
* @param config the {@link Dhis2Config}.
* @return the encoded string.
*/
public static String getBasicAuthString( Dhis2Config config )
{
String value = config.getUsername() + ":" + config.getPassword();
return "Basic " + Base64.getEncoder().encodeToString( value.getBytes() );
}
/**
* Adds basic authentication to the given request using the Authorization header.
*
* @param request the {@link HttpUriRequestBase}.
* @param config the {@link Dhis2Config}.
* @param class.
* @return the request.
*/
public static T withBasicAuth( T request, Dhis2Config config )
{
request.setHeader( HttpHeaders.AUTHORIZATION, getBasicAuthString( config ) );
return request;
}
/**
* Builds on URI without throwing checked exceptions.
*
* @param uriBuilder the {@link URIBuilder}.
* @return a {@link URI}.
*/
public static URI build( URIBuilder uriBuilder )
{
try
{
return uriBuilder.build();
}
catch ( URISyntaxException ex )
{
throw new RuntimeException( ex );
}
}
/**
* Returns the string representing the given URI. The URI is decoded.
*
* @param uri the {@link URI}.
* @return a URI string.
*/
public static String asString( URI uri )
{
try
{
return URLDecoder.decode( uri.toString(), StandardCharsets.UTF_8.toString() );
}
catch ( UnsupportedEncodingException ex )
{
throw new RuntimeException( ex );
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy