HttpURLConnection失败,出现404错误

时间:2011-11-13 20:03:10

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

我的httpURLConnection失败,出现404 - 找不到资源错误。相同的URL适用于我的firefox海报并返回200 / ok。这两个应用程序(webapp和URL-app)都位于同一台机器上。我从另一个帖子中发现,当相同的URL在浏览器中工作时,我需要添加2行以使其工作 -

urlConnection.setRequestProperty(“User-Agent”,“Mozilla / 5.0(compatible)”); 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);

}

1 个答案:

答案 0 :(得分:-2)

尝试再次发送请求。在我的项目中,我使用Apache HttpClient发送请求&amp;很多时候404错误通过再次发送请求来解决。 (但不是所有的时间)

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

404错误应该是'资源暂时不可用'。