Access .htaccess protected file Android

◇◆丶佛笑我妖孽 提交于 2020-01-17 06:52:22

问题


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:


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();
}


来源:https://stackoverflow.com/questions/37883327/access-htaccess-protected-file-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!