【问题标题】:HttpURLConnection fails with 404 ErrorHttpURLConnection 失败并出现 404 错误
【发布时间】:2011-12-28 04:43:24
【问题描述】:

我的 httpURLConnection 失败并出现 404 - Resource not Found 错误。相同的 URL 适用于我的 firefox 海报并返回 200/ok。两个应用程序(webapp 和 URL-app)都位于同一台机器上。我从另一个线程中发现,我需要在 2 行以下添加以使其在浏览器中使用相同的 URL 时起作用-

urlConnection.setRequestProperty("User-Agent","Mozilla/5.0(兼容)"); urlConnection.setRequestProperty("接受","/");

不幸的是,添加以上行并不能解决问题。我在下面的代码中做错了吗?任何有用的建议将不胜感激。

{

String computerName = InetAddress.getLocalHost().getHostName();

url = new URL("http://"+computerName+":8080"+"/cerprovider/devices");
        urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDefaultUseCaches(false);
        urlConnection.setUseCaches(false);
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Connection",     "Keep-Alive");
        urlConnection.setRequestProperty("Content-Length", Integer.toString(Integer.MAX_VALUE));
        urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept","*/*");
        urlConnection.setConnectTimeout(500);

        // Create I/O streams
        outStream = new DataOutputStream(urlConnection.getOutputStream());
        //inStream = new DataInputStream(urlConnection.getInputStream());
        // Send request
        outStream.writeBytes(<blah>.toString());
        outStream.flush();
        outStream.close();

        BufferedReader in = null;
        String responseErrorString = "";
        _tracer.info("Response code --"+urlConnection.getResponseCode());
        InputStream error = urlConnection.getErrorStream();
        _tracer.info("Error from the connection --"+error.toString());
        StringBuilder buf = new StringBuilder();
        for(int c = -1; (c = error.read()) != -1; )
            buf.append((char)c);
        responseErrorString = new String (buf);
        _tracer.info("responseErrorString--"+responseErrorString);

}

【问题讨论】:

  • 您要执行什么样的请求 - POST、GET 等?你的请求有效载荷是什么?请记住,如果您将 URL 直接粘贴到浏览器中,您正在执行一个没有表单数据的简单 GET,并且看起来您的代码正在尝试做更多的事情。
  • 我正在做一个“POST”,我正在尝试我的 post 请求,内容类型为 text/plain 在 Firefox 海报工具上。它通过正常并返回 200/ok。我的请求数据是一个逗号分隔的简单字符串。

标签: java http url http-status-code-404


【解决方案1】:

尝试再次发送请求。在我的项目中,我使用 Apache HttpClient 发送请求,并且多次通过再次发送请求来解决 404 错误。 (但不是一直)

还可以在 firefox 上使用 httpfox 插件来检查您发送请求时到底发生了什么。

404 错误应该是因为“资源暂时不可用”。

【讨论】:

  • 也是为什么你把这行: urlConnection.setRequestProperty("Content-Length", Integer.toString(Integer.MAX_VALUE));这是必需的吗?
  • 我解决了这个问题。出于某种原因,我的代码不喜欢 - urlConnection.setRequestProperty("Accept","/");将其更改为接受 text/plain 解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-16
  • 2016-08-02
  • 2018-02-24
  • 2021-02-14
  • 2018-03-03
  • 2012-09-24
相关资源
最近更新 更多