[英]I want to return response in XML form from REST API in java
我在java中使用REST API來獲取圖像文件並保存在服務器上我希望以XML格式返回上傳圖像的路徑,但不知道如何操作。目前它在瀏覽器中將響應作為字符串返回。
這是我的代碼。
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();
}
}
}
如果要從Rest返回xml,請嘗試使用某些字段創建Object。 對象和字段將具有@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")
。 兩者都是一樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.