Friday, 30 June 2017

Android: Sending headers with HttpURLConnection

This post includes the usage and implementation of HttpURLConnection to download a file from a URL along with sending the required headers with the http request. Through this post you will also learn to send custom headers along with the request to your http url.

The usage and implementation of HttpURLConnection is very simple as follows:

1. In your project, just add the following method where you want to download the file. Just pass the url from which you want to download the file, as the parameter to the below method.

private void downloadFileFromHttpURL(String your_url){
            
            URL url = new URL(your_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // default headers for the request
            connection.addRequestProperty("Content-Type", "application/json");

            // custom headers for the request
            connection.addRequestProperty("customHeaderKey1", "HEADER_VALUE");
            connection.addRequestProperty("customHeaderKey2", "HEADER_VALUE");

            // check for the connection of url
            int response = connection.getResponseCode();
            if (response == 200) { // connected to the URL
LogWriter.write("LOG_TAG", "Is downloading..?");     

BufferedInputStream inStream = new BufferedInputStream(connection.getInputStream());
                // provide the path to save the downloaded file
                FileOutputStream fileStream = new FileOutputStream("YOUR_FILE_PATH");

                // BufferesOutputStream is used to write the downloaded file
                BufferedOutputStream outStream = new BufferedOutputStream(fileStream);

                byte[] buffer = new byte[16384];
                int len = 0;
                while ((len = inStream.read(buffer, 0, 16384)) != -1) {
                    LogWriter.write("LOG_TAG", "Yes downloading..");
                    outStream.write(buffer, 0, len);
                }
                outStream.flush();
                inStream.close();
                outStream.close();
            } else {
                // disconnect from URL if not connected  
                connection.disconnect();
                return null;
            }
            // disconnect from URL when the download is completed  
            connection.disconnect();
    }

That's all.
The above method will download the file from the url and save it to the path provided by you.
There are other option as well that you can use with HttpURLConnection which are follows:
   
      connection.setUseCaches(false);
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");

Note:
HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called.
Other HTTP methods (OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with setRequestMethod(String).


Share and comment if any issues.

22 comments:

  1. Haidilao is a famous hot pot restaurant known for its wide variety of food choices. The menu offers fresh ingredients like thinly sliced meat, seafood, vegetables, noodles, and tofu, which you cook yourself in flavorful broths.

    ReplyDelete
  2. Renovlies muur is een soort wandbekleding die wordt gebruikt om muren er glad en netjes uit te laten zien. Het is een sterk, duurzaam materiaal dat op de muur wordt geplakt om scheuren, oneffenheden of oud behang af te dekken.

    ReplyDelete
  3. Twisted Tea is a refreshing hard iced tea known for its smooth, sweet flavor that makes it a popular choice for parties and casual gatherings. Curious how much sugar is in a twisted tea? Despite its light and fruity taste, it contains a notable sugar content that’s worth checking if you’re mindful of your intake.

    ReplyDelete
  4. The first thing I noticed on laser247 was how fast the site reacted. No unnecessary animations or popups. It just works. Clean design, smooth loading, and a pleasant overall vibe. A nicely balanced platform.

    ReplyDelete
  5. GTA San Andreas APK is one of the most iconic action-adventure games available for Android devices, bringing the full open-world experience of San Andreas to your mobile screen. This game allows players to explore the vast cities, countryside, and deserts of the fictional state while completing thrilling missions, engaging in car chases, and customizing characters. With its smooth controls, immersive graphics, and countless side activities, the GTA San Andreas APK provides a complete gaming experience similar to the console version. Downloading the APK lets fans enjoy this classic game anytime, anywhere, without the limitations of a PC or console, making it highly relevant for mobile gamers looking for adventure and excitement on the go.https://gtasanandreasgame.com

    ReplyDelete
  6. If you are looking for more detailed information, updates, or services, you can simply visit this site to explore everything in one place. The website is designed to provide users with easy navigation, clear content, and quick access to the latest features or announcements. Whether you are searching for guides, downloads, or general information, visiting the site will help you find what you need without any hassle. Just click through and discover all the available sections for a better experience.
    https://apknoor.com/

    ReplyDelete
  7. Margo game download is gaining attention among mobile users who enjoy online gaming experiences with simple controls and engaging gameplay. The game is usually promoted as an APK-based application that can be installed on Android devices, offering quick access without going through official app stores. Players are often attracted by its smooth interface, fast loading features, and different in-game modes that keep the experience interesting. However, before downloading any Margo game APK from third-party sources, users should always be careful and make sure the file is from a trusted and secure website to avoid security risks or unwanted software on their devices.

    ReplyDelete
  8. The m666 game is an online gaming platform that is often promoted as a mobile-based entertainment app featuring casino-style games, slots, and reward-based challenges. It is designed to attract users with simple gameplay, fast registration, and the promise of earning bonuses or in-game rewards. However, such apps usually operate outside official app stores, which raises concerns about security, data privacy, and financial risk. Users should be careful when downloading or using the M666 Game, as unofficial gaming platforms may not provide proper user protection or regulated fair play systems. It is always recommended to rely on trusted and licensed gaming sources to ensure a safe and secure experience.

    ReplyDelete
  9. Rent an ATM Machine is also highly relevant for businesses looking to create an additional source of passive income. Every time a customer withdraws cash, the business owner can earn a small transaction fee, which gradually adds up over time without requiring extra effort. This makes it a smart investment for shop owners, fuel stations, supermarkets, and other high-traffic locations. Moreover, having an ATM on-site enhances customer convenience, as people prefer places where they can quickly access cash without searching for a bank. It also helps improve customer retention, as visitors are more likely to return to locations that provide useful services like cash withdrawal.

    ReplyDelete
  10. World cup football shirts hold a strong cultural and commercial relevance in the world of sports, especially around the time of the FIFA World Cup. These shirts are more than just team kits; they represent national pride, identity, and global unity as fans proudly wear their country’s colors to support their teams. Each World Cup brings new and iconic jersey designs that often become historic collectibles, especially when associated with memorable matches or winning moments. Beyond the tournament, these shirts also influence fashion trends, sports merchandising, and fan culture worldwide, making them highly relevant in both sports and lifestyle markets.

    ReplyDelete
  11. PVZ Fusion APK es una versión creada por fans que añade nuevas plantas, zombis y mecánicas innovadoras al clásico juego de estrategia Plants vs. Zombies. Los jugadores pueden disfrutar de desafíos únicos, combinaciones especiales y contenido renovado que hace cada partida más emocionante. La jugabilidad mantiene la esencia original mientras incorpora características creativas y entretenidas. Muchos usuarios también buscan pvz fusion 3.7 para conocer las últimas novedades y actualizaciones del proyecto.

    ReplyDelete
  12. pkslots Best Money App is designed for users in Pakistan who are interested in online gaming and entertainment through a mobile-friendly platform. It offers convenient access to different games, simple navigation, and an easy-to-use interface for Android users. Players should always review the app’s terms, security features, and applicable local laws before using any real-money gaming service, and they should play responsibly.

    ReplyDelete
  13. PPK365 App is a mobile gaming platform designed to provide users with a convenient way to explore different online games from their smartphones. The app features a simple interface and easy navigation, making it accessible for both new and experienced users. Before installing PK365 App, users should verify that they are downloading it from a trusted source and review the platform’s terms, privacy practices, and applicable local regulations.

    ReplyDelete
  14. rs33 game download gives players a convenient way to access a mobile gaming platform designed for entertainment and quick gameplay. Users looking for an RS33 Game Download can explore its available games, interface, account features, and overall experience from a compatible device. Before installing any APK, it is important to use a trusted source, check the required permissions, and confirm that the version is compatible with your device. Players should also review the platform’s terms and local regulations before using any real-money features.

    ReplyDelete
  15. Workplace Risk Assessment is an essential process for identifying potential hazards and evaluating the risks they may create for employees, visitors, and others in the workplace. It involves examining work activities, equipment, substances, and working conditions to determine what could cause harm and what control measures are needed. A well-prepared risk assessment helps organizations reduce accidents, improve workplace safety, comply with health and safety requirements, and create a safer working environment. Regular reviews are important to ensure that controls remain effective when workplace conditions, processes, or equipment change.

    ReplyDelete
  16. D97 Game a mobile gaming platform that offers players an easy way to explore and enjoy a variety of games. With a simple interface, smooth navigation, and convenient access across compatible devices, D97 Game focuses on providing an engaging gaming experience. Users can explore available game options, learn about features, and stay updated with the latest D97 Game information and updates.

    ReplyDelete
  17. teenpati blue is a popular online card game focused on the traditional Teen Patti experience. It offers a simple interface, engaging gameplay, and multiple table options for players who enjoy quick card rounds. Users can explore different game modes, learn basic Teen Patti rules, and improve their understanding of card combinations while enjoying a digital version of this classic game.

    ReplyDelete
  18. teenpattisignupis a convenient starting point for users interested in exploring online Teen Patti gaming platforms. The signup process typically allows new players to create an account, access available game features, and manage their profiles from one place. Before registering, users should review the platform’s terms, privacy policy, age requirements, and any applicable local laws. For a safer experience, use trusted platforms and avoid sharing sensitive account information with unknown sources.

    ReplyDelete
  19. CashPKR is an online gaming platform that users may explore for information about its features, registration process, app installation, and latest updates. The CashPKR Game experience may appeal to users looking for mobile entertainment and an easy-to-navigate interface. Before downloading the CashPKR APK, users should check the official source, review the app’s permissions, and confirm that the version is compatible with their Android device. It is also important to understand the platform’s terms and conditions, privacy policy, and any financial risks associated with deposits or reward-based activities. By staying informed and using trusted sources, users can make better decisions when exploring CashPKR and its available features.

    ReplyDelete
  20. APKSPINZ Installation Guide helps users understand how to download and install the APKSPINZ app on their Android devices. Before starting the installation, users should check their device compatibility, available storage space, and internet connection. If the app is provided as an APK file, download it only from a trusted and verified source, then review the file before proceeding. Depending on the Android version, users may need to allow installation from the specific source used to download the file. Once the installation is complete, open the app and follow the on-screen instructions to get started. This guide makes the APKSPINZ installation process easier to understand while encouraging users to prioritize device security, verify app permissions, and keep their software updated for a safer experience.

    ReplyDelete
  21. Rummy Latest Version offers players an updated way to enjoy the classic card game on their Android devices. With a refreshed interface, improved navigation, and potentially enhanced gameplay features, the latest version can provide a smoother and more convenient gaming experience. Players can explore different Rummy modes, practice their card-matching skills, and learn the rules at their own pace, depending on the features supported by the app. Before downloading or installing the latest Rummy APK, users should check the version details, device compatibility, and required permissions. It is also important to download the app from a trusted source to reduce security risks. Whether you are a beginner or an experienced card-game enthusiast, the Rummy Latest Version can be an option for enjoying digital Rummy while playing responsibly and following the platform’s rules.

    ReplyDelete
  22. Car owners can benefit from regular maintenance, practical troubleshooting tips, and reliable automotive information to keep their vehicles running smoothly. https://carownerdesk.com offers a relevant resource for exploring car care guidance and vehicle-related topics. Understanding your vehicle’s warning signs and following a proper maintenance routine can help prevent unexpected breakdowns. Simple checks and timely servicing can also support safer, more confident driving.

    ReplyDelete