不支援HTTP版本:505

时间:2019-05-19 00:59:00

标签: java selenium brokenimage

我已经编写了Selenium / Java脚本来查找网站上的损坏图像。在34张图像中,有2张图像抛出505错误代码(不支持HTTP版本)。

这是我的代码

    HttpURLConnection huc = null;
    int respCode = 200;
    huc = (HttpURLConnection) (new URL(url).openConnection());
    huc.setRequestMethod("HEAD");

    huc.setConnectTimeout(2000);
    huc.connect();
    respCode = huc.getResponseCode();

    if (respCode >= 400) {
        System.out.println(url + " is a broken with error code:" + respCode);
    } else {
        System.out.println(url + " is a good");
    }

505 Errors:
https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Soja-CampoDeSojaConFocoYDesenfoque-0_71-1 Desktop(new)?$callToActionCard_tablet$ is a broken with error code:505

https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Cenital-VistaCenitalDeCampo-0_71-1 Desktop(new)?$callToActionCard_desktop$ is a broken with error code:505


Few successful responses:
https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Campo-PersonasCaminandoEnElCampoConAtardecer-0_71-1 Desktop(new)?$callToActionCard_desktop$ is a good
https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Campo-PersonasCaminandoEnElCampoConAtardecer-0_71-1 Desktop(new)?$callToActionCard_tablet$ is a good
https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Campo-PersonasCaminandoEnElCampoConAtardecer-0_71-1 Desktop(new)?$callToActionCard_mobile$ is a good
https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Soja-CampoDeSojaConFocoYDesenfoque-0_71-1 Desktop(new)?$callToActionCard_desktop$ is a good 

2 个答案:

答案 0 :(得分:1)

问题与URL一起使用,它包含空格。您可以将Java URL编码器用于一般解决方案:Java URL encoding of query string parameters

对于您而言,只需按以下步骤替换%20中的空格:

        String url = "https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Soja-CampoDeSojaConFocoYDesenfoque-0_71-1%20Desktop(new)?$callToActionCard_tablet$";
    HttpURLConnection huc = null;
    int respCode = 200;
    huc = (HttpURLConnection) (new URL(url).openConnection());
    huc.setRequestMethod("HEAD");

    huc.setConnectTimeout(2000);
    huc.connect();
    respCode = huc.getResponseCode();

    if (respCode >= 400) {
        System.out.println(url + " is a broken with error code:" + respCode);
    } else {
        System.out.println(url + " is a good");
    }

输出:

https://s7d4.scene7.com/is/image/DuPontCorteva/IMG-Soja-CampoDeSojaConFocoYDesenfoque-0_71-1%20Desktop(new)?$callToActionCard_tablet$ is a good

答案 1 :(得分:1)

鉴于您使用了Selenium和Java,应该将OkHttp库“免费”作为Selenium transitive dependencies的一部分。

因此,您可以将图像检查逻辑修改为:

OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder().url(url).method("HEAD", null).build();
Response response = client.newCall(request).execute();
int respCode = response.code();

由于特殊的URL Encoding导致您当前的请求失败,OkHttp客户端会自动处理characters which are not allowed in URLs

您可能还想obtain browser cookies并将其添加到您的请求中,因为端点可能需要基于cookie的身份验证