{"id":619,"date":"2017-12-14T18:51:23","date_gmt":"2017-12-14T10:51:23","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=619"},"modified":"2018-09-05T10:58:55","modified_gmt":"2018-09-05T02:58:55","slug":"how-to-send-an-http-request-to-a-http-basic-authentication-endpoint-in-java-without-using-any-external-libraries","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-send-an-http-request-to-a-http-basic-authentication-endpoint-in-java-without-using-any-external-libraries\/","title":{"rendered":"How to send an HTTP request to a HTTP Basic Authentication endpoint in Java without using any external libraries"},"content":{"rendered":"<p>One common task for Java developers is to write codes that communicate with API endpoints. Chances are these endpoints could use HTTP Basic Authentication for authenticating the HTTP request sender. <\/p>\n<p>Although there are good libraries to help us craft and send HTTP requests to a web server in Java, I prefer to use the Java core library so as to keep my Java program lightweight. <\/p>\n<p>Referencing my earlier post on <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-construct-a-http-request-to-an-endpoint-with-http-basic-authentication\/\" target=\"_blank\">how to construct a HTTP request to an endpoint with HTTP basic authentication<\/a>, this post documents how to send an HTTP request to a HTTP Basic Authentication endpoint in Java without using any external libraries.    <\/p>\n<h2>Using httpbin.org to test our HTTP request with HTTP Basic Authentication<\/h2>\n<p>For the sake of brevity, we will use an endpoint from <a href=\"http:\/\/httpbin.org\/\" rel=\"noopener\" target=\"_blank\">httpbin.org<\/a> to test out the Java codes that we are going to write. <\/p>\n<p>This endpoint is available at <a href=\"http:\/\/httpbin.org\/basic-auth\/user\/passwd\" rel=\"noopener\" target=\"_blank\">http:\/\/httpbin.org\/basic-auth\/user\/passwd<\/a>. It expects a HTTP Basic Authentication request with:<\/p>\n<ul>\n<li>HTTP GET as the HTTP method,<\/li>\n<li><strong>user<\/strong> as the username<\/li>\n<li>and <strong>passwd<\/strong> as the password<\/li>\n<\/ul>\n<h2>Java codes for generating a Base64 encoded String payload from a username and password pair <\/h2>\n<p>The first step in crafting a HTTP request for a HTTP Basic Authentication endpoint is to generate a Base64 encoded String payload from the username and password. Lucky for us, <a href=\"http:\/\/www.oracle.com\/technetwork\/java\/javase\/overview\/java8-2100321.html\" rel=\"noopener\" target=\"_blank\">Java 8<\/a> provided <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/util\/Base64.html\"><code>java.util.Base64<\/code><\/a> to help us with Base64 encoding.<\/p>\n<p>The following Java 8 codes generate a Base64 encoded String payload with <strong>user<\/strong> as the username and <strong>passwd<\/strong> as the password:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nString usernameColonPassword = &quot;user:passwd&quot;;\r\nString basicAuthPayload = &quot;Basic &quot; + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());\r\n<\/pre>\n<p>To generate the HTTP Basic Authentication payload, we simply:<\/p>\n<ol>\n<li>concatenate the username, a colon and the password,<\/li>\n<li>pass the concatenated String as bytes to <code>Base64.getEncoder().encodeToString<\/code> to get a Base64 encoded String,<\/li>\n<li>and prepend the Base64 encode String with the String \"Basic \".<\/li>\n<\/ol>\n<h2>Java codes for sending HTTP request to the HTTP Basic Authentication endpoint<\/h2>\n<p>With the <code>basicAuthPayload<\/code>, we can then proceed with crafting and sending the HTTP request to the HTTP Basic Authentication endpoint. <\/p>\n<p>To avoid external libraries, we can use the following classes that are provided by the Java code library for sending the HTTP request:<\/p>\n<ul>\n<li>java.io.BufferedReader<\/li>\n<li>java.io.BufferedWriter<\/li>\n<li>java.io.File<\/li>\n<li>java.io.FileInputStream<\/li>\n<li>java.io.InputStreamReader<\/li>\n<li>java.io.OutputStream<\/li>\n<li>java.io.OutputStreamWriter<\/li>\n<li>java.net.HttpURLConnection<\/li>\n<li>java.net.URL<\/li>\n<\/ul>\n<p>And write the following codes to send a HTTP GET request to a HTTP Basic Authentication endpoint:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nBufferedReader httpResponseReader = null;\r\ntry {\r\n    \/\/ Connect to the web server endpoint\r\n    URL serverUrl = new URL(&quot;http:\/\/httpbin.org\/basic-auth\/user\/passwd&quot;);\r\n    HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();\r\n\r\n    \/\/ Set HTTP method as GET\r\n    urlConnection.setRequestMethod(&quot;GET&quot;);\r\n\r\n    \/\/ Include the HTTP Basic Authentication payload\r\n    urlConnection.addRequestProperty(&quot;Authorization&quot;, basicAuthPayload);\r\n\r\n    \/\/ Read response from web server, which will trigger HTTP Basic Authentication request to be sent.\r\n    httpResponseReader =\r\n            new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\r\n    String lineRead;\r\n    while((lineRead = httpResponseReader.readLine()) != null) {\r\n        System.out.println(lineRead);\r\n    }\r\n\r\n} catch (IOException ioe) {\r\n    ioe.printStackTrace();\r\n} finally {\r\n\r\n    if (httpResponseReader != null) {\r\n        try {\r\n            httpResponseReader.close();\r\n        } catch (IOException ioe) {\r\n            \/\/ Close quietly\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<h2>Putting it together<\/h2>\n<p>The following is a Java main class that contains all the codes that we had discussed:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStreamReader;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.util.Base64;\r\n\r\n\r\npublic class HttpBasicAuthenticationExample {\r\n\r\n    public static void main(String&#x5B;] args) {\r\n\r\n        String usernameColonPassword = &quot;user:passwd&quot;;\r\n        String basicAuthPayload = &quot;Basic &quot; + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes());\r\n\r\n        BufferedReader httpResponseReader = null;\r\n        try {\r\n            \/\/ Connect to the web server endpoint\r\n            URL serverUrl = new URL(&quot;http:\/\/httpbin.org\/basic-auth\/user\/passwd&quot;);\r\n            HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();\r\n\r\n            \/\/ Set HTTP method as GET\r\n            urlConnection.setRequestMethod(&quot;GET&quot;);\r\n\r\n            \/\/ Include the HTTP Basic Authentication payload\r\n            urlConnection.addRequestProperty(&quot;Authorization&quot;, basicAuthPayload);\r\n\r\n            \/\/ Read response from web server, which will trigger HTTP Basic Authentication request to be sent.\r\n            httpResponseReader =\r\n                    new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));\r\n            String lineRead;\r\n            while((lineRead = httpResponseReader.readLine()) != null) {\r\n                System.out.println(lineRead);\r\n            }\r\n\r\n        } catch (IOException ioe) {\r\n            ioe.printStackTrace();\r\n        } finally {\r\n\r\n            if (httpResponseReader != null) {\r\n                try {\r\n                    httpResponseReader.close();\r\n                } catch (IOException ioe) {\r\n                    \/\/ Close quietly\r\n                }\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n}\r\n<\/pre>\n<p>Running the above code will produce the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\n{\r\n  &quot;authenticated&quot;: true, \r\n  &quot;user&quot;: &quot;user&quot;\r\n}\r\n<\/pre>\n<p>You may wish to change the String literal that is assigned to the <code>usernameColonPassword<\/code> variable and observe what happens. <\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-9Z\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9Z&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9Z&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F619&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>One common task for Java developers is to write codes that communicate with API endpoints. Chances are these endpoints could use HTTP Basic Authentication for authenticating the HTTP request sender. <\/p>\n<p>Although there are good libraries to help us craft and send HTTP requests to a web server in Java, I prefer to use the Java core library so as to keep my Java program lightweight. <\/p>\n<p>Referencing my earlier post on <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-construct-a-http-request-to-an-endpoint-with-http-basic-authentication\/\" target=\"_blank\">how to construct a HTTP request to an endpoint with HTTP basic authentication<\/a>, this post documents how to send an HTTP request to a HTTP Basic Authentication endpoint in Java without using any external libraries.    <\/p>\n","protected":false},"author":1,"featured_media":1220,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[471,23,403,199,6,463,464,465,466,467,468,469,462,470,472],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-9Z","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/619"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=619"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/619\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1220"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=619"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=619"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=619"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}