Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I got different results when call simple GET Request with curl and java okhttp

I call below URL using cURL

curl 'http://username:password@192.168.1.108/merlin/Login.cgi'

and I get proper response

{ "Session" : "0xb3e01810", "result" : { "message" : "OK", "num" : 200 } }

I get the same response from browser (directly open link), postman and even with NodeJs,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but I get response code 401 when send GET_Request to this url using okhttp in java

my java code with okhttp is

    Request request = new Request.Builder()
                            .url("http://username:password@192.168.1.108/merlin/Login.cgi")
                            .build();

    try {
      com.squareup.okhttp.Response response = client.newCall(request).execute();
      System.out.println(response.code());
    } catch (IOException e) {
      e.printStackTrace();
    }

>Solution :

Use basic authentication. Having username and password in the url, separated with :, is the same as basic authentication. I tested and it’s ok. my snippet is:

OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://192.168.1.108/merlin/Login.cgi")
                .header("Authorization", "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes()))
                .get().build();

        try (Response response = client.newCall(request).execute()) {
            assert response.body() != null;
            String res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading