0

I'd like to access a file that is protected by .htaccess in my Android app. Below is what I need to get just a file, but not .htaccess protected. I don't know where I can put my credentials... Can someone help me with adding credentials to this? Or propose another way to collect the file? Thanks in advance :)

        InputStream inputStream = null;
        URL url = null;
        try {
            url = new URL(THENEEDEDURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            // Starts the query
            conn.connect();
            inputStream = conn.getInputStream();

            InputStreamReader reader = new InputStreamReader(inputStream);
            Gson gson = new GsonBuilder().create();
            winnendeCodes = gson.fromJson(reader, WedstrijdCode[].class);
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

1 Answer 1

1

You need to use setRequestProperty on your HttpURLConnection object:

InputStream inputStream = null;
URL url = null;
try {
    url = new URL(THENEEDEDURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // might not work, instead use bellow code
    // String htpasswd = Base64.encode("username:password");
    String htpasswd = Base64.encodeToString(("username:password").getBytes("UTF-8"), Base64.NO_WRAP); 
    conn.setRequestProperty("Authorization", "Basic " + htpasswd);
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    inputStream = conn.getInputStream();

    InputStreamReader reader = new InputStreamReader(inputStream);
    Gson gson = new GsonBuilder().create();
    winnendeCodes = gson.fromJson(reader, WedstrijdCode[].class);
    conn.disconnect();
} catch (IOException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.