从IntentService调用时,HttpURLConnection返回404

时间:2013-02-22 11:13:08

标签: 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中调用完全相同的代码,上传文件并成功完成。

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

1 个答案:

答案 0 :(得分:5)

尝试打印您尝试打开的网址,您可能会发现它有问题...也许这只是一个缺失的斜线; - )

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