我正在开发使用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,则收到的文件不可读(在将它保存到磁盘后)。
我该如何满足我的要求?任何人都可以提出解决方案
你能发布你的客户端和服务器代码吗?没有这一点,很难说出什么问题。 – 2012-01-09 06:35:07
感谢您的回应。我添加了一些代码。 – pierus 2012-01-09 10:15:42