Joe*_*son 3 java android apache-httpcomponents
我正试图通过他们的新API通过此处记录的方法将照片上传到热门服务Dailybooth .
问题是服务器响应:
<html><head><title>411 Length Required</title>...
Run Code Online (Sandbox Code Playgroud)
我用来发送这些数据的代码在这里:
// 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();
}
Run Code Online (Sandbox Code Playgroud)
我不知道我做错了什么.
小智 8
您正在使用描述MultipartEntity内容的其中一个StringBody和InputStreamBody类.查看源代码,StringBody.getContentLength()返回字符串的长度,但InputStreamBody总是返回-1,我想这是为了你需要将一些数据上传到服务器而不知道它的大小的情况,并开始上传,而数据来自流.
如果您希望能够设置内容长度,那么您需要事先了解流的大小,如果是这样的话,您可以做什么InputStreamBody:
new InputStreamBody(f, snap_url.getLastPathSegment()) {
public long getContentLength() {
return /*your length*/;
}
}
Run Code Online (Sandbox Code Playgroud)
或者将你的数据流转储到一个byte[]数组中然后传递ByteArrayInputStream给它InputStreamBody,当然这样你就失去了流媒体能力,因为你需要在发送数据之前将数据缓存到内存中......
正如你所说,你正在研究图像,这个图像File是否有机会?如果是这样,你也有FileBody正确的回报content-length.
| 归档时间: |
|
| 查看次数: |
2555 次 |
| 最近记录: |