3

我正在尝试通过此处记录的方法通过他们的新 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();
}

我不知道我做错了什么。

4

1 回答 1

8

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

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

new InputStreamBody(f, snap_url.getLastPathSegment()) {

    public long getContentLength() {
        return /*your length*/;
    }
}

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

正如您所说,您正在处理图像,这些图像File是偶然的吗?如果是这样,您也可以FileBody返回正确的content-length.

于 2011-01-16T17:19:17.507 回答