Skip to main content

Overview

The ApiClient class provides a type-safe Java interface for all backend API operations. It handles HTTP communication, JSON serialization, and authentication token management. Location: src/main/java/com/borjaalmazan/entrega1_1/apiManager/ApiClient.java

Constructor

public ApiClient(String baseUrl)
baseUrl
String
required
The base URL of the API server (e.g., https://api.example.com)
Example:
ApiClient client = new ApiClient("https://dimedianet-backend.azurewebsites.net");

Authentication Methods

login()

Authenticates a user and returns a JWT token.
public String login(String email, String password) throws Exception
email
String
required
User’s email address
password
String
required
User’s password (plain text)
return
String
JWT token for authenticated requests. The method checks for token, access_token, or jwt fields in the response.
HTTP Request:
  • Method: POST
  • Endpoint: /api/Auth/login
  • Content-Type: application/json
Throws:
  • IOException - If login fails (e.g., invalid credentials, network error)
  • Exception - For other errors (JSON parsing, etc.)
Example:
try {
    ApiClient client = new ApiClient("https://api.example.com");
    String jwt = client.login("[email protected]", "myPassword123");
    System.out.println("Logged in successfully. Token: " + jwt);
} catch (IOException e) {
    System.err.println("Login failed: " + e.getMessage());
}

User Methods

getMe()

Retrieves the current authenticated user’s profile.
public Usuari getMe(String jwt) throws Exception
jwt
String
required
JWT authentication token from login()
return
Usuari
User object containing profile information
HTTP Request:
  • Method: GET
  • Endpoint: /api/users/me
  • Authorization: Bearer token
Example:
Usuari user = client.getMe(jwt);
System.out.println("Welcome, " + user.nickName + "!");
System.out.println("Email: " + user.email);
System.out.println("User ID: " + user.id);

getNickName()

Retrieves a user’s nickname by their ID.
public String getNickName(int id, String jwt) throws Exception
id
int
required
The user ID
jwt
String
required
JWT authentication token
return
String
The user’s nickname. Handles both JSON and plain text responses.
HTTP Request:
  • Method: GET
  • Endpoint: /api/users/{id}/nickname
Example:
String nickname = client.getNickName(42, jwt);
System.out.println("User 42's nickname: " + nickname);

Media Retrieval Methods

getAllMedia()

Retrieves all media files from the server.
public List<Media> getAllMedia(String jwt) throws Exception
jwt
String
required
JWT authentication token
return
List<Media>
List of all media objects in the system
HTTP Request:
  • Method: GET
  • Endpoint: /api/files/all
Example:
List<Media> allMedia = client.getAllMedia(jwt);
for (Media m : allMedia) {
    System.out.println(m.mediaFileName + " uploaded by user " + m.userId);
}

getMyMedia()

Retrieves media files uploaded by the current user.
public List<Media> getMyMedia(String jwt) throws Exception
jwt
String
required
JWT authentication token
return
List<Media>
List of media objects owned by the authenticated user
HTTP Request:
  • Method: GET
  • Endpoint: /api/files/me
Example:
List<Media> myMedia = client.getMyMedia(jwt);
System.out.println("You have " + myMedia.size() + " media files");

getMediaByUser()

Retrieves media files uploaded by a specific user.
public List<Media> getMediaByUser(int userId, String jwt) throws Exception
userId
int
required
The user ID to query
jwt
String
required
JWT authentication token
return
List<Media>
List of media objects uploaded by the specified user
HTTP Request:
  • Method: GET
  • Endpoint: /api/files/user/{userId}

getMediaAddedSince()

Retrieves media files added after a specific timestamp.
public List<Media> getMediaAddedSince(OffsetDateTime from, String jwt) throws Exception
public List<Media> getMediaAddedSince(String isoFrom, String jwt) throws Exception
from
OffsetDateTime | String
required
ISO-8601 timestamp (e.g., 2025-11-18T12:00:00Z). Accepts either OffsetDateTime object or String.
jwt
String
required
JWT authentication token
return
List<Media>
List of media objects added since the specified timestamp
HTTP Request:
  • Method: GET
  • Endpoint: /api/files/added-since?from={timestamp}&container={container}
This method is used by the polling component to sync new media files periodically.
Example:
// Using String
List<Media> newMedia = client.getMediaAddedSince("2025-11-18T12:00:00Z", jwt);

// Using OffsetDateTime
OffsetDateTime lastCheck = OffsetDateTime.now().minusHours(1);
List<Media> recentMedia = client.getMediaAddedSince(lastCheck, jwt);

listBlobs()

Lists all blobs in the default container.
public String listBlobs(String jwt) throws Exception
jwt
String
required
JWT authentication token
return
String
Raw JSON response containing blob list
HTTP Request:
  • Method: GET
  • Endpoint: /api/files?container=dimedianetblobs

Media Upload/Download Methods

download()

Downloads a media file by ID and saves it to disk.
public void download(int id, File destFile, String jwt) throws Exception
id
int
required
The media ID to download
destFile
File
required
Destination file path where the media will be saved
jwt
String
required
JWT authentication token
HTTP Request:
  • Method: GET
  • Endpoint: /api/files/{id}?container=dimedianetblobs
  • Response: Binary stream
Throws:
  • FileNotFoundException - If media with the specified ID is not found (404)
  • IOException - For other download errors
Example:
File outputFile = new File("/downloads/video.mp4");
try {
    client.download(123, outputFile, jwt);
    System.out.println("Downloaded to: " + outputFile.getAbsolutePath());
} catch (FileNotFoundException e) {
    System.err.println("Media not found: " + e.getMessage());
}

uploadFileMultipart()

Uploads a file to the server using multipart/form-data encoding.
public String uploadFileMultipart(File file, String downloadedFromUrl, String jwt) throws Exception
file
File
required
The file to upload
downloadedFromUrl
String
Optional URL indicating where the file was originally downloaded from
jwt
String
required
JWT authentication token
return
String
Raw JSON response from server (typically contains uploaded media metadata)
HTTP Request:
  • Method: POST
  • Endpoint: /api/files/upload
  • Content-Type: multipart/form-data
  • Form Fields:
    • file - The binary file data
    • downloadedFromUrl - Optional source URL
    • container - Blob container name (dimedianetblobs)
Example:
File videoFile = new File("/path/to/video.mp4");
String sourceUrl = "https://youtube.com/watch?v=example";

try {
    String response = client.uploadFileMultipart(videoFile, sourceUrl, jwt);
    System.out.println("Upload successful: " + response);
} catch (IOException e) {
    System.err.println("Upload failed: " + e.getMessage());
}

Media Model

The Media class represents a media file in the system. Location: src/main/java/com/borjaalmazan/entrega1_1/apiManager/Media.java
public class Media {
    @JsonProperty("id")
    public int id;
    
    @JsonProperty("userId")
    public int userId;
    
    @JsonProperty("downloadedFromUrl")
    public String downloadedFromUrl;
    
    @JsonProperty("mediaFileName")
    public String mediaFileName;
    
    @JsonProperty("mediaMimeType")
    public String mediaMimeType;
    
    @JsonProperty("blobNameGuid")
    public String blobNameGuid;
    
    @JsonProperty("blobUrl")
    public String blobUrl;
}
id
int
Unique media identifier
userId
int
ID of the user who uploaded the media
downloadedFromUrl
String
Original source URL (if applicable)
mediaFileName
String
Original filename of the uploaded media
mediaMimeType
String
MIME type (e.g., video/mp4, image/jpeg)
blobNameGuid
String
Unique blob identifier in Azure Storage
blobUrl
String
Direct URL to access the blob

Configuration

Default Settings

private final String defaultBlobContainer = "dimedianetblobs";
Timeouts:
  • Connection timeout: 10 seconds
  • Request timeout: 30 seconds

Custom HttpClient

The client is created with:
this.client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(10))
    .build();

Error Handling

All methods throw Exception. Common error patterns:
try {
    String jwt = client.login(email, password);
} catch (IOException e) {
    // "Login failed: 401 -> Invalid credentials"
    handleAuthError(e);
}
Always implement proper exception handling. Network errors, authentication failures, and server errors can occur at any time.

See Also

Authentication

JWT token management and user models

API Overview

High-level API architecture and flow

Build docs developers (and LLMs) love