Android RestFul API调用post方法

时间:2015-04-10 11:31:54

标签: android rest

我怀疑如何发布我的REST端点URL如下所示的数据:

http://my.domain.com/Upload/{ID}/{IMAGE_CONTENT_AS_BYTE_ARRAY}

我需要将Image内容作为字节数组字符串发送到此端点方法。但由于charater长度可以超过2000个字符长度,因此我可能无法发送IMAGE,如果它的巨大,因为一切都作为URL字符串的一部分。如何输入IMAGE_CONTENT_AS_BYTE_ARRAY的数据。     此外,我没有任何关键,所以我可以把它放在名字对。请建议!

2 个答案:

答案 0 :(得分:2)

试试这段代码:

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);

答案 1 :(得分:0)

上传图片或文件的最佳方式是使用多部分数据格式。 以下是上传图片的示例代码。

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();
    }
}