0

我正在学习 Java REST Web 服务,我正在尝试使用 Android 上传图像文件。下面是客户端和服务器代码。我收到 Http Status code 415: The server denied this request because the request entity is in an format not supported by the requested resource for the requested method 。有什么问题?谢谢你。

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

}
4

1 回答 1

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);
            }
于 2013-10-02T13:10:39.753 回答