我正在开发一个使用 Dropbox API 的 Jersey 服务。
我需要向我的服务发布一个通用文件(该服务将能够管理各种文件,就像您可以使用 Dropbox API 一样)。
客户端
所以,我实现了一个简单的客户端:
- 打开文件,
- 创建到 URL 的连接,
- 设置正确的 HTTP 方法,
- 创建一个
FileInputStream
并使用字节缓冲区将文件写入连接的输出流。
这是客户端测试代码。
public class Client {
public static void main(String args[]) throws IOException, InterruptedException {
String target = "http://localhost:8080/DCService/REST/professor/upload";
URL putUrl = new URL(target);
HttpURLConnection connection = (HttpURLConnection) putUrl.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-Type", "application/pdf");
OutputStream os = connection.getOutputStream();
InputStream is = new FileInputStream("welcome.pdf");
byte buf[] = new byte[1024];
int len;
int lung = 0;
while ((len = is.read(buf)) > 0) {
System.out.print(len);
lung += len;
is.read(buf);
os.write(buf, 0, len);
}
}
}
服务器端
我有一个方法:
- 得到一个
InputStream
作为参数, - 创建一个与原始文件具有相同名称和类型的文件。
下面的代码实现了一个测试方法来接收一个特定的 PDF 文件。
@PUT
@Path("/upload")
@Consumes("application/pdf")
public Response uploadMaterial(InputStream is) throws IOException {
String name = "info";
String type = "exerc";
String description = "not defined";
Integer c = 10;
Integer p = 131;
File f = null;
try {
f = new File("welcome.pdf");
OutputStream out = new FileOutputStream(f);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
out.close();
is.close();
System.out.println("\nFile is created........");
} catch (IOException e) {
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
//I need to pass a java.io.file object to this method
professorManager.uploadMaterial(name, type, description, c,p, f);
return Response.ok("<result>File " + name + " was uploaded</result>").build();
}
此实现仅适用于文本文件。如果我尝试发送一个简单的 PDF,则接收到的文件是不可读的(在我将其保存在磁盘上之后)。
我怎样才能满足我的要求?谁能建议我解决方案?