我正在使用 Apache HttpClient 4.0 作为我的网络爬虫。我发现奇怪的行为是:我试图通过 HTTP GET 方法获取页面并获取有关 404 HTTP 错误的响应。但如果我尝试使用浏览器获取该页面,则成功完成。
详细信息: 1.我通过这种方式将多部分表单上传到服务器:
HttpPost httpPost = new HttpPost("http://[host here]/in.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("method", new StringBody("post"));
entity.addPart("key", new StringBody("223fwe0923fjf23"));
FileBody fileBody = new FileBody(new File("photo.jpg"), "image/jpeg");
entity.addPart("file", fileBody);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();
String responseString = "";
if (result != null) {
InputStream inputStream = result.getContent();
byte[] buffer = new byte[1024];
while(inputStream.read(buffer) > 0)
responseString += new String(buffer);
result.consumeContent();
}
上传成功结束。
我从网络服务器获取一些结果:
HttpGet httpGet = new HttpGet("http://[host here]/res.php?key="+myKey+"&action=get&id="+id); HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity();
我在执行方法运行时收到 ClientProtocolException。我正在使用 log4j 调试这种情况。服务器回答“404 Not Found”。但我的浏览器加载该页面没有任何问题。
有人可以帮我吗?
谢谢。
最佳答案
我必须注意这个问题与网络服务器无关。如果我不将 FileBody 添加到多部分表单数据中,则不会发生异常,一切正常,没有 HTTP 404。
关于java - Apache HttpClient 4.0。奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1676019/