【问题标题】:Invalid Content-Length is sent to the server?无效的 Content-Length 被发送到服务器?
【发布时间】:2011-01-16 15:10:04
【问题描述】:

我正在尝试通过 documented here 方法通过他们的新 API 将照片上传到流行的服务 Dailybooth。

问题是服务器响应:

<html><head><title>411 Length Required</title>...

我用来发送这些数据的代码在这里:

// 2: Build request
HttpClient httpclient = new DefaultHttpClient();
SharedPreferences settings = DailyboothShared.getPrefs(DailyboothTakePhoto.this);
String oauth_token = settings.getString("oauth_token", "");
HttpPost httppost = new HttpPost(
        "https://api.dailybooth.com/v1/pictures.json?oauth_token=" + oauth_token);
Log.d("upload", "Facebook: " + facebook);
Log.d("upload", "Twitter: " + twitter);
try {
    InputStream f = getContentResolver().openInputStream(snap_url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("picture", new InputStreamBody(f, snap_url.getLastPathSegment()));
    entity.addPart("blurb", new StringBody(blurb));
    entity.addPart("publish_to[facebook]", new StringBody(facebook));
    entity.addPart("publish_to[twiter]", new StringBody(twitter));
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    Log.d("upload", response.toString());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 200) {
        // do something?
    } else {
        Log.d("upload", "Something went wrong :/");
    }
    Log.d("upload", EntityUtils.toString(response.getEntity()));
} catch (Exception ex) {
    ex.printStackTrace();
}

我不知道我做错了什么。

【问题讨论】:

    标签: java android apache-httpcomponents


    【解决方案1】:

    您正在使用描述 MultipartEntity 内容的 StringBodyInputStreamBody 类。查看源代码,StringBody.getContentLength() 返回字符串的长度,但InputStreamBody 始终返回-1,我猜这是针对您需要在不知道其大小的情况下将一些数据上传到服务器的情况,并在数据进入流时开始上传。

    如果您希望能够设置内容长度,那么您需要事先知道您的流的大小,如果是这种情况,您可以做的是这样设置InputStreamBody

    new InputStreamBody(f, snap_url.getLastPathSegment()) {
    
        public long getContentLength() {
            return /*your length*/;
        }
    }
    

    或将您的流转储到byte[] 数组中并将ByteArrayInputStream 传递给InputStreamBody,当然这样做您会失去流传输能力,因为您需要在发送数据之前将数据缓存在内存中...

    正如您所说,您正在处理图像,这些图像是File 吗?如果是这样,您还有 FileBody 返回正确的 content-length

    【讨论】:

    • 谢谢,我会尝试这些建议。不幸的是,我试图轻松获取“文件”对象,尽管 Android 系统不希望我能够这样做。
    • 怎么看不到文件?我很确定你可以在 android 上这样做,因为 java.io.File 是 SDK 的一部分。可能是一些权限问题
    • 我正在尝试从相机和其他应用程序中获取文件,这些应用程序将 url 返回为“content://blah/blah/blah”,由于某种原因文件无法打开。但是,我改为使用文件描述符,它允许我“统计”长度并且它起作用了。谢谢:D
    猜你喜欢
    • 2020-07-07
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2021-06-07
    相关资源
    最近更新 更多