我对如何发布数据有疑问,我的REST端点URL如下所示:
http://my.domain.com/Upload/{ID}/{IMAGE_CONTENT_AS_BYTE_ARRAY}我需要将图像内容作为字节数组字符串发送到此端点方法。但由于字符长度可以超过2000个字符的长度,我可能无法发送的图像,如果它的巨大,因为一切都作为URL字符串的一部分。如何放入IMAGE_CONTENT_AS_BYTE_ARRAY的数据。另外,我没有任何关键字,所以我可以把它放在namevalue pair.Please suggest中!
发布于 2015-04-10 19:49:09
尝试以下代码:
MultipartEntityBuilder multipartEntity;
String URL = "My server url";
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
bitmap.compress(CompressFormat.JPEG, 75, byteArrayOutputStream);
byte[] byteData = byteArrayOutputStream.toByteArray();
ByteArrayBody byteArrayBody = new ByteArrayBody(byteData, "image"); // second parameter is the name of the image )
// send the package
multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("image", byteArrayBody);发布于 2015-04-10 19:50:26
上传图像或文件的最佳方式是使用多部分数据格式。这是一个上传图片的示例代码。
public static void postMultiPart(String url, File image)
{
final android.net.http.AndroidHttpClient client = android.net.http.AndroidHttpClient.newInstance("sample");
// enable redirects
HttpClientParams.setRedirecting(client.getParams(), true);
final String encoded_url = encodeURL(url);
final org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(encoded_url);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("profile", new FileBody(image));
post.setEntity(mpEntity);
org.apache.http.HttpResponse response;
try {
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
if (!(statusCode == org.apache.http.HttpStatus.SC_OK || statusCode == org.apache.http.HttpStatus.SC_CREATED)) {
Log.i("Error:","Check....."+"Error " + statusCode + " while posting data to " + encoded_url + "\nreason phrase: " + response.getStatusLine().getReasonPhrase());
return;
}
Log.i("SUCCESS:","Check....."+Base64.encodeToString(md.digest(), Base64.DEFAULT));
} catch (IOException e) {
} finally {
client.close();
}
}https://stackoverflow.com/questions/29560357
复制相似问题