【发布时间】:2017-10-05 07:59:51
【问题描述】:
任务
“通过在端点 /images 上使用 HTTP POST 请求发送图像,并带有 multipart-form-encoded 或 base64 编码数据参数。”
我将 Cloudsight API 用于我的图像识别项目。参考http://docs.cloudsight.apiary.io/#reference/0/images-collection/send-an-image-for-identification
问题
我需要从画廊发送一张编码为 base64 格式的图像,但我收到服务器错误 500。我似乎无法在我的代码中找到问题,可能图像编码不正确?
代码
private String uploadData(String url) {
String sResponse = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url+"/images");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Authorization", "CloudSight API_KEY");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String encImage = Base64.encodeToString(data, Base64.DEFAULT);
JSONObject obj = new JSONObject();
obj.put("remote_image_url",encImage );
obj.put("locale", "en");
httpPost.setEntity(new StringEntity(obj.toString()));
HttpResponse response = httpClient.execute(httpPost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
sResponse = inputStreamToString(
response.getEntity().getContent()).toString();
Log.i("ResponseString", sResponse);
Log.i("code", responseCode+"");
} catch (Exception ex) {
ex.printStackTrace();
}
return sResponse;
}
private class uploadImage1 extends AsyncTask<String, String, String>{
ProgressBar progressBar = new ProgressBar(getApplication(), null, android.R.attr.progressBarStyleSmall);
protected void onPreExecute() {
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String url = params[0];
String sResponse = uploadData(url);
return sResponse;
}
}
编辑
“注意:我们建议图像分辨率不高于 1024x,JPEG 压缩级别在 5-8 之间。否则我们会在内部调整图像大小,这可能会减慢请求过程。”
所以我需要在发送之前调整图像大小?你能分享一些例子吗?
【问题讨论】:
-
Server 500 用于内部服务器错误。请向服务器团队寻求解决方案。
-
"注意:我们建议图像分辨率不高于 1024x,JPEG 压缩级别在 5-8 之间。否则,我们会在内部调整图像大小,这可能会减慢请求过程。"所以我需要在发送之前调整我的图像大小?你能分享一些例子吗?
-
欢迎来到 SO。 1) 更加努力地格式化你的代码 2) 你为什么使用 sn-ps? 3)这是一项任务吗?下次请正确格式化,以便我们了解源任务是什么以及您提出的问题是什么 4) 问一个特定的问题,而不是多个随机和广泛的问题 - 没有人会与您分享完整解决方案的示例,这不是这个网站是为。 5) 发帖前请仔细阅读:stackoverflow.com/help/asking
-
您好,感谢您的建议。抱歉问题结构不好,我更新了我正在使用的 API 的参考
-
嗨 -
remote_image_url用于网络上图像的 url。如果您自己以 base64 编码发送图像,那么您想要的参数就是image。
标签: android base64 http-post httprequest cloudsight