【发布时间】: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