0

Здравствуйте. Имеется код:

int size = sWebList.size();
for(int i=0;i<(size);i++){
    int j = sWebList.size();
    if (j!=0){
        String sURL = sWebList.get(0);
        System.out.println("----------------------------"+sURL+"-------------------------------------");
        sWebList.remove(0);
        try{
            URL url = new URL("http://www."+sURL+"/robots.txt");
            try{
                LineNumberReader reader = new LineNumberReader(new InputStreamReader(url.openStream()));
                String string = reader.readLine();
                while(string!=null){
                    sRobots.add(string);
                    string = reader.readLine();
                }
                reader.close();
            }catch(IOException e){
                e.printStackTrace();
            }
            for (String line : sRobots) {
                System.out.println(line);
            }
            sRobots.clear();
        }catch (MalformedURLException ex){
            ex.printStackTrace();
        }                
    }
}

Циклом из sWebList берётся имя сайта, читается и выводится robots.txt. Некоторые сайты, если не обнаруживают User-Agent, выбрасывают Exception. Как в данный код добавить setRequestProperty("User-Agent", "Mozilla/5.0");?

Можно и так сделать:

URLConnection uc;
StringBuilder parserContentFromUrl = new StringBuilder();
String urlString = "http://www."+sURL+"/robots.txt";
try{
    url = new URL(urlString);
    uc = url.openConnection();
    uc.addRequestProperty("User-Agent","Mozilla/5.0");
    uc.connect();
    uc.getInputStream();
    BufferedInputStream in = new BufferedInputStream(uc.getInputStream());
    int ch;
    while((ch = in.read()) != -1){
        parserContentFromUrl.append((char) ch);
    }
    System.out.println(parserContentFromUrl);
} catch (Exception ex){
    ex.printStackTrace();
}

Но мне нужно, чтобы в дальнейшем в sRobots были строки, тогда как во втором варианте побайтово получается. Помогите разобраться.

2
  • Разобрался:URL url = new URL("http://www."+sURL+"/robots.txt"); URLConnection uc = url.openConnection(); uc.addRequestProperty("User-Agent", "Mozilla/5.0"); uc.connect(); try{ LineNumberReader reader = new LineNumberReader(new InputStreamReader(uc.getInputStream()));
    – Cenzor
    17 июл 2017 в 5:59
  • 1
    Если разобрались - оформите, пожалуйста, как ответ. 17 июл 2017 в 7:58

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.