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を送信しようとすると、受信したファイルが読み取れなくなります(ディスクに保存した後)。
どうすれば要件を満たすことができますか?誰かが私に解決策を提案できますか?