[英]Java Jersey 415 (Unsupported Media Type)
我對目前正在構建的REST接口Iam有疑問。 由於沒有可用的資源,Iam通常是前端專家,現在處理后端的東西。 因此,請耐心等待我:-)。
這是Class Iam所說的:
/**
*
* @author User
*/
@Path("/excel")
public class Excel {
private Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://tmp/";
@POST
@Path("/export")
//@Consumes(MediaType.APPLICATION_JSON)
@Consumes({"application/xml","application/json"})
public Response writeFile(FileContent fileContent){
//Check if anything is null, if so return a server error code 500
String startDateStr = new Date().toString();
try {
JsonParser parser = new JsonParser();
JsonObject element = (JsonObject) parser.parse(fileContent.getContent());
String fileName = startDateStr + Integer.toString(new Random().nextInt(100)) + ".xls";
FileInformation fi = new FileInformation(
fileName,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
File file = new File(fileName);
WritableWorkbook workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet(fileName, 0);
int i = 0;
while(element.get(Integer.toString(i)) != null && !element.get(Integer.toString(i)).getAsJsonArray().isJsonNull()) {
JsonArray line = element.get(Integer.toString(i)).getAsJsonArray();
System.out.println(i);
for(int n = 0; n < line.size(); n++)
{
System.out.println(line.get(n).toString());
Label label = new Label(n,i, line.get(n).toString());
sheet.addCell(label);
}
i++;
}
workbook.write();
workbook.close();
Runnable r = new DeleteThread(file);
new Thread(r).start();
return Response.status(201).entity(fi).header("Access-Control-Allow-Origin", "*").build();
} catch (NullPointerException | IOException | WriteException e ) {
System.out.println(e);
return Response.status(500).build();
}
}
@GET
@Path("/export")
@Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
public Response serveFile(@QueryParam("fileName") String fileName){
File file = new File(fileName);
Response.ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=" + fileName);
return response.build();
}
@PUT
@Path("/import")
@Produces
public Response putFile() {
/*@FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();
FileHelper.saveFile(fileInputStream, filePath);*/
return Response.status(200).entity("Hallo Friend").build();
}
}
這是我的POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.range_plan_viz.rest</groupId>
<artifactId>jerseyrangeplan</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jerseyrangeplan Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>rangePlanVizRest</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<server>TomcatServer</server>
<path>/restRangePlan</path>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>
這是請求有效負載的映射器類:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.range_plan_viz.wrapper;
/**
*
* @author User
*/
public class FileContent {
private String content;
public FileContent(String content){
setContent(content);
}
/**
* @return the content
*/
public String getContent() {
return content;
}
/**
* @param content the content to set
*/
public void setContent(String content) {
this.content = content;
}
}
這是響應有效負載的映射器:
package org.range_plan_viz.wrapper;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by User on 12.02.2015.
*/
@XmlRootElement
public final class FileInformation {
private String fileName;
private String contentType;
/**
* Default constructor
* @param content The content of the excel file published by the UI
* @param fileName The name of the file that should be generated published by the UI
* @param contentType The contenType of the file
*/
public FileInformation(
String fileName,
String contentType
){
setFileName(fileName);
setContentType(contentType);
}
/**
* Getter of the fileName
* @return {String} The fileName of the file that should be generated
*/
public String getFileName() {
return fileName;
}
/**
* The setter of the fileName
* @param {String} fileName The fileName of the file that should be
* generated
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* The getter of the content type
* @return {String} The contentType of the file that should be generated
*/
public String getContentType() {
return contentType;
}
/**
* The setter of the content type
* @param {String} contentType The contentType of the app that should be
* generated
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Override
public String toString() {
return "FileInformation [fileName=" + getFileName() + ", contenType=" + getContentType() + "]";
}
}
這是測試它的JavaScript:
var a =[BigDataMock],
url = "http://localhost:8084/jerseyrangeplan/rest/excel/export"
$.ajax({
url: url,
method: 'post',
crossDomain: true,
contentType: "application/json",
dataType: "json",
data:{
content: JSON.stringify(a)
},
success: function(result, status, xhr) {
window.location.assign(url + "?fileName=" + result.fileName);
},
error: function (responseData, textStatus, errorThrown) {
console.log('POST failed.');
}
});
我要做的基本上是提取Excel前端的大型數據集,然后下載文件。 我已經嘗試過表單方法,但是它僅適用於小型數據集。 我們的對象中有10000個成員,並且該表單將字符串分割成字符串,導致后端出現問題。 我也嘗試使用excelbuilder.js,但這也不起作用。 從Java后端無法正確解釋生成excel文件后發送的字節流。 現在,我要保存Excel文件,然后立即在回調中觸發下載。
但是我一直收到415不支持的媒體類型錯誤。 我也遇到了CORS過濾器的問題,它似乎無法正常工作。
有人可以幫忙嗎?
提前致謝,
塞巴斯蒂安
似乎主要的問題是您沒有配置用於處理JSON的MessageBodyReader
。 您在類路徑上有jersey-media-json-jackson
,但仍然需要注冊該提供程序。 這就是為什么不支持的媒體類型。 如果Jersey找不到提供者來處理轉換,這就是您將獲得的狀態。
如果您使用的是web.xml,則可以使用
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
jersey.web.stackoverflow, <!-- your package -->
org.codehaus.jackson.jaxrs <!-- jackson package -->
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
如果您使用的是ResourceConfig
類,則只需執行
public class AppConfig extends ResourceConfig {
public AppConfig() {
register(JacksonFeature.class);
}
}
解決此問題后可以期待什么
不確定您如何發送數據,我不知道它是什么BigDataMock
,但是如果傑克遜無法讀取數據,則可能會收到400錯誤的請求
注釋中也提到了,您的GET重定向方法中的@Produces
很有可能會遇到另一個問題。 不支持該內容類型,您將需要為其編寫自定義MessageBodyWriter
,或者改為簡單地使用application/octect-stream
。
您還需要FileContent
的默認(無參數)構造FileContent
。 傑克遜需要這個來創建POJO。
UPDATE
所以我猜@Produces
不是問題。 我能夠解決問題,只需解決主要問題,第一個項目符號和最后一個項目符號。 我也改變了
String startDateStr = new Date().toString();
// TO
long startDateStr = new Date().getTime();
我猜(至少對於Windows用戶而言),這是一種錯誤的文件名格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.