Java for Uploading Documents in Rossum API
This Java code shows how to upload a document automatically using Rossum API to a particular Rossum queue.
This Java example demonstrates how to upload a document using Rossum API to a particular Rossum queue. Set the options at the beginning of the code – they store your credentials, and also the identifier of the queue to upload in. You can find out the queue id by looking at your main screen URL, it is the number 12345 in https://example.rossum.app/annotations/12345
.
See the reference API documentation for more details about how to use the upload API.
import org.apache.http.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.FileEntity;
import org.json.*;
import java.io.File;
public class JavaExample {
public static String USERNAME = "SOME_USERNAME";
public static String PASSWORD = "SOME_PASSWORD";
public static String QUEUE_ID = "SOME_QUEUE_ID";
public static String API_URL = "https://example.rossum.app/api";
public static String FILE_PATH = "PATH_TO_SOME_FILE";
public static String login(String url, String username, String password){
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
System.out.println("Logging");
HttpPost postRequest = new HttpPost(url);
StringEntity params = new StringEntity(String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password));
postRequest.addHeader("content-type", "application/json");
postRequest.setEntity(params);
HttpResponse httpResponse = httpclient.execute(postRequest);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
JSONObject obj = new JSONObject(EntityUtils.toString(entity));
String key = obj.getString("key");
return key;
}
}catch(Exception e){
e.printStackTrace();
}finally {
httpclient.getConnectionManager().shutdown();
}
return null;
}
public static void upload(String key, String url, String filePath){
DefaultHttpClient httpclient = new DefaultHttpClient();
try{
HttpPost postRequest = new HttpPost(url);
File file = new File(filePath);
FileEntity params = new FileEntity(file);
postRequest.setHeader(HttpHeaders.AUTHORIZATION, "token " + key);
postRequest.setHeader("Content-Disposition", String.format("attachment; filename=%s", file.getName()));
postRequest.setEntity(params);
HttpResponse httpResponse = httpclient.execute(postRequest);
HttpEntity entity = httpResponse.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
}catch(Exception e){
e.printStackTrace();
}finally {
httpclient.getConnectionManager().shutdown();
}
}
public static void main(String[] args) {
String key = login(String.format(API_URL+"%s", "/v1/auth/login"), USERNAME, PASSWORD);
upload(key, String.format(API_URL+"%s"+"%s"+"%s", "/v1/queues/", QUEUE_ID, "/upload"), FILE_PATH);
}
}
Updated about 1 year ago
What’s Next