尝试从Android客户端上传图像时出现不支持的媒体类型错误

时间:2013-09-30 16:00:26

标签: java android web-services rest

我正在学习Java REST Web服务,我正在尝试使用Android上传图像文件。以下是客户端和服务器代码。我收到Http状态代码415:服务器拒绝了此请求,因为请求实体的格式不受所请求方法所请求资源的支持。可能有什么不对?谢谢。

Android客户端代码如下所示:

HttpClient httpclient = new DefaultHttpClient();

        FileBody fileContent = new FileBody(new File(
                Environment.getExternalStorageDirectory() + File.separator
                        + "Pictures/" + IMAGE_FILE_NAME));

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("file", fileContent);

        HttpResponse response = null;
        try {       
                HttpPost httppost = new HttpPost(url);
                httppost.setEntity(multipartEntity);
                response = httpclient.execute(httppost);

        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
        }

,服务器代码如下所示:

    @POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail) {

    String uploadedFileLocation = "C://uploadedFiles/"
            + fileDetail.getFileName();

    // save it
    saveToFile(uploadedInputStream, uploadedFileLocation);

    String output = "File uploaded via Jersey based RESTFul Webservice to: "
            + uploadedFileLocation;

    return Response.status(200).entity(output).build();

}

1 个答案:

答案 0 :(得分:0)

我终于能够解决这个问题了。以下是有效的代码。谢谢。

Bitmap bitmap = BitmapFactory.decodeFile(Environment
                .getExternalStorageDirectory()
                + File.separator
                + "Pictures/" + IMAGE_FILE_NAME);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
        byte[] byte_arr = stream.toByteArray();

        ByteArrayBody fileBody = new ByteArrayBody(byte_arr,
                "imageFileName.jpg");

        MultipartEntity multipartEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);

        multipartEntity.addPart("file", fileBody);

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = null;
            try {

                HttpPost httppost = new HttpPost(url);
                httppost.setEntity(multipartEntity);
                response = httpclient.execute(httppost);


               } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
            }