小编spe*_*ads的帖子

从IntentService调用时,HttpURLConnection返回404

我正在尝试构建一个使用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();
    }                                       
}
Run Code Online (Sandbox Code Playgroud)

在IntentService onHandleIntent方法中,我总是得到404(或者在不检查conn.getResponseCode()时得到FileNotFoundException).

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

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

android

1
推荐指数
1
解决办法
3214
查看次数

标签 统计

android ×1