Back to Projects

Easy HTTP Request

Android Java

A lightweight wrapper for Android's HttpURLConnection. It simplifies asynchronous networking by handling background tasks, parameter encoding, and callbacks for GET, POST, file uploads, and image downloading.

Integration

This library consists of a single Java class. No Gradle dependencies are required.

Installation
  1. Download or copy the HttpRequest.java file.
  2. Paste it into your Android project's source package (e.g., com.example.myapp.utils).
  3. Import the class wherever you need to make network calls.

Permissions

Ensure you have added the internet permission to your AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" /> <!-- If reading files --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

GET Request

Performs an asynchronous GET request. Parameters are automatically URL-encoded and appended to the URL.

// 1. Prepare Parameters HashMap<String, String> params = new HashMap<>(); params.put("user_id", "101"); params.put("token", "xyz-123"); // 2. Execute Request HttpRequest.GET( "https://api.example.com/data", params, response -> { // 3. Handle Response (UI Thread) Log.d("API", "Response: " + response); } );

POST Request

Sends data via POST method. Content-Type is set to application/x-www-form-urlencoded.

Note: The current implementation waits for the result [synchronous behavior via .get()].
Ensure you handle threading appropriately if calling from the main thread in older Android versions.
// 1. Prepare Form Data HashMap<String, String> params = new HashMap<>(); params.put("username", "malek"); params.put("password", "123456"); // 2. Execute POST HttpRequest.POST( "https://api.example.com/login", params, response -> { if(response.contains("Success")) { Toast.makeText(context, "Login Successful", Toast.LENGTH_SHORT).show(); } } );

Upload File

Uploads a local file to a server using multipart/form-data.

String url = "https://api.example.com/upload.php"; String paramName = "uploaded_file"; // $_FILES['uploaded_file'] String filePath = "/sdcard/DCIM/image.jpg"; HttpRequest.Upload_File( url, paramName, filePath, response -> { Log.d("Upload", "Server replied: " + response); } );

Download Image

Fetches an image from a URL and returns it as an Android Bitmap object.

String imgUrl = "https://example.com/avatar.png"; HttpRequest.Download_Image( imgUrl, bitmap -> { if (bitmap != null) { // Set image to ImageView myImageView.setImageBitmap(bitmap); } } );

API Reference

Static Method Description
GET(url, params, callback) Performs an async GET request. Params appended to URL.
POST(url, params, callback) Performs a POST request with form-urlencoded body.
Upload_File(url, key, path, cb) Multipart upload of a file from local storage.
Download_Image(url, callback) Downloads an image and returns a Bitmap object.