android - 从 IntentService 调用时,HttpURLConnection 返回 404

标签 android

我正在尝试构建一个使用 REST Api 上传文件的 IntentService。

我可以从我的主 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(或在不检查 conn.getResponseCode() 时得到 FileNotFoundException)。

在我的主 Activity 中调用完全相同的代码,上传文件并成功完成。

我不知道为什么会这样?有什么想法吗?

最佳答案

尝试打印您要打开的 URL,您可能会发现它有问题...也许它只是缺少一个斜杠 ;-)

404 是未找到的 HTTP 错误..意味着该 URL 在该服务器上无效。

关于android - 从 IntentService 调用时,HttpURLConnection 返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15022855/

相关文章:

java - 在java中从xml设置数字

java - Listview 不再向其中的 spinner 注册 itemClickEvent

android - Django request.body 数据不完整

java - 无法通过 setActionBar 设置工具栏(Android)

android - 表格行内的 TextView 中的优先级

java - 如何在 Fragment 中动态添加 TableRow?

java - 按钮在 Android 应用程序中不起作用

Android 2.1/2.2蓝牙串口连接台式电脑

android - ListView 的索引越界异常

android - 有什么方法可以加快 Android 模拟器的速度