1
我试图构建一个使用REST Api上载文件的IntentService。从IntentService调用时,HttpURLConnection返回404
我可以从我的主Activity启动IntentService,IntentService可以将消息传回Activity,所以我知道IntentService正在工作。
我的问题是,当我运行这段代码:
@Override
protected void onHandleIntent(Intent intent) {
// do the uploading stuff
try {
URL url = new URL(this.url + fileName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
BufferedInputStream buffInputStream = new BufferedInputStream(new FileInputStream(filePath));
BufferedOutputStream buffOutputStream = new BufferedOutputStream(conn.getOutputStream());
HttpUtils.copyBufferStream(buffInputStream, buffOutputStream);
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedInputStream responseBufferedInput = new BufferedInputStream(conn.getInputStream());
byte[] body = HttpUtils.readStream(responseBufferedInput);
result = HttpUtils.convertBytesToString(body);
Log.e("Result:", result);
}else{
Log.e("conn.getResponseCode()", Integer.toString(conn.getResponseCode()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
在IntentService onHandleIntent方法
,我总是得到一个404(或FileNotFoundException异常时不检查conn.getResponseCode())。
在我的主Activity中调用完全相同的代码,上传文件并成功完成。
我不知道为什么会发生这种情况?有任何想法吗?
好点。如果URL格式不正确或编码不正确,这肯定会返回404。在这种情况下,url完全是它应该的。我在主Activity中的相同HttpURLConnection代码中测试了相同的url,并且在浏览器中的REST Api控制台中测试了相同的url,并且它工作正常。 – speedynomads 2013-02-22 11:25:37
相关提示!祝你好运! – 2013-02-22 12:17:22
Doh!事实证明,这个网址实际上是错误的,实际上有一个缺失的斜线;谢谢! – speedynomads 2013-02-22 12:25:19