Invalid Content-Length is sent to the server?
I'm trying to upload a photo to the popular service Dailybooth via their new API throug开发者_如何转开发h the method documented here.
The problem is that the server is responding with:
<html><head><title>411 Length Required</title>...
The code I'm using to send this data is here:
// 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();
}
I've got no idea what I'm doing wrong.
You are using either StringBody
and InputStreamBody
classes which describe the content of your MultipartEntity. Looking at the sources, StringBody.getContentLength()
returns the length of the string, but InputStreamBody
always return -1
, and I guess this is done for the case you need to upload some data to the server without knowing the size of it, and start uploading while data comes to the stream.
If you want to be able to set the content length then you need to know the size of your stream beforehand, what you can do if that's the case is to set the InputStreamBody
that way:
new InputStreamBody(f, snap_url.getLastPathSegment()) {
public long getContentLength() {
return /*your length*/;
}
}
or dump your stream in a byte[]
array and pass ByteArrayInputStream
to the InputStreamBody
, of course doing so you loose the streaming ability as you need to cache your data in memory before sending it over...
As you said you are working on images, are this images File
by any chance? If so you also have FileBody
that return the correct content-length
.
精彩评论