Search code examples
javajsonhttp-status-code-401

Reading JSON from a URL in Java avoiding 401 error


I have been trying to read the json data from a url but I am keep getting error 401. Is there any way to add authentication method with base 64 encoder to get the json data? Please let me know. Thanks

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class jsonFetcher {

public static void loadDocument() throws Exception {
    URL url = new URL("http://cmvd9k0n.dev.cm.par.emea.cib:8080/api/v1/topology/summary");
    try {
        File destination = new File("dest.json");
        // Copy bytes from the URL to the destination file.
        FileUtils.copyURLToFile(url, destination);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Solution

  • To perform this request with the authentication headers you will need to use a HTTP Client. Depending on your needs and Java version that can be the Apache Http Client, the Java 11 native Http Client, Spring Rest Template, or many others.

    Using Apache HTTP Client:

    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.apache.http.client.methods.RequestBuilder;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.HttpResponse;
    
    HttpClient client = HttpClients.custom().build();
    HttpUriRequest request = RequestBuilder.get()
     .setUri("http://cmvd9k0n.dev.cm.par.emea.cib:8080/api/v1/topology/summary")
     .setHeader(HttpHeaders.AUTHORIZATION, "yourBase64EncodedCreds")
     .build();
    HttpResponse response = client.execute(request);
    

    the json data you want will be within the HttpResponse object.