【问题标题】:I want to return response in XML form from REST API in java我想从 Java 中的 REST API 以 XML 形式返回响应
【发布时间】:2016-01-27 13:51:15
【问题描述】:

我在 java 中有 REST API,它获取图像文件并保存在服务器上浏览器。

这是我的代码。

package com.javacodegeeks.enterprise.rest.jersey;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/files")
public class JerseyFileUpload {

    private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/home/hassan/Downloads/";

    /**
     * Upload a File
     */

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();

        // save the file to the server
        saveFile(fileInputStream, filePath);

        String output = "File saved to server location : " + filePath;

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

    }

    // save uploaded file to a defined location on the server
    private void saveFile(InputStream uploadedInputStream,
            String serverLocation) {

        try {
            OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            outpuStream = new FileOutputStream(new File(serverLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }
            outpuStream.flush();
            outpuStream.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

【问题讨论】:

  • 这并不能解决您声称的问题,但我希望图像文件的位置将在响应的 Location 标头中返回。
  • output 是一个字符串。您需要返回一个带有@XmlElement注释的类的实体(实例)
  • 我可以在同一个类中使用 Produces 注释,因为 Consumes 注释也在这里我可以同时使用两者吗。@RobAu 如何使用 @XmlElement,因为我很新。

标签: java xml api rest


【解决方案1】:

如果您想从 Rest 返回 xml,请尝试使用一些字段创建 Object。并且 Object 和 field 将具有 @XmlRootElement @XmlElement 并将 @Produces("application/xml") 放在方法签名之上。

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("application/xml")
    public Response uploadFile(...){
         //body
   }

您也可以使用@produces(MediaType.APPLICATION_XML) 代替@Produces("application/xml")。两者都是一样的。

【讨论】:

猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2014-09-11
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
相关资源
最近更新 更多