OkHTTP:
There are several ways to upload the file. OKHTTP is a one of a client to call
an api to upload file to the server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String uploadfile(String sourceID,String accessToken) { | |
String fileUploadID = null; | |
InputStream is = null; | |
Response response = null; | |
try { | |
// String sourceID = projectDetails.getString("sourceID"); // | |
String test = "this is from text"; | |
is = new FileInputStream("C:\\Users\\lKadariya\\Desktop\\Test | |
\\DTtest\\TestFile\\original_testcases\\100\\100sample.docx"); | |
byte []content = IOUtils.toByteArray(is); | |
//byte []content = test.getBytes(StandardCharsets.UTF_8); | |
String uri = "https://transport-stg.transperfect.com/api/files/upload? | |
filename=test.docx&targetFolderId="+sourceID; | |
final MediaType MEDIA_TYPE = MediaType.parse("multipart/form-data"); | |
OkHttpClient client = new OkHttpClient(); | |
RequestBody requestBody = new MultipartBody.Builder() | |
.setType(MultipartBody.FORM) | |
.addPart( | |
Headers.of("Content-Disposition", "form-data;"), | |
RequestBody.create(MEDIA_TYPE, content) | |
) | |
.build(); | |
Request request = new Request.Builder() | |
.header("Authorization", "Bearer " + accessToken) | |
.url(uri) | |
.post(requestBody) | |
.build(); | |
response = client.newCall(request).execute(); | |
int responseCode = response.code(); | |
if (responseCode != 200) { | |
System.out.println("uploadfile: Did not receive token. HTTP code: " + | |
responseCode + " responseBody:"+response.body()); | |
} else { | |
String taggedResult = response.body().string(); | |
// System.out.println(taggedResult); | |
Object json = new JSONTokener(taggedResult).nextValue(); | |
JSONObject jobj = null; | |
if(json instanceof JSONObject){ | |
jobj = new JSONObject(taggedResult) ; | |
} else if(json instanceof JSONArray){ | |
jobj = (JSONObject)new JSONArray(taggedResult).get(0); | |
} | |
Object error = jobj.getString("error"); | |
if (error == "null"){ | |
fileUploadID = (String)jobj.get("id"); | |
} | |
} | |
} catch (NoRouteToHostException re) { | |
System.out.println("uploadfile: unable to route to host."+re); | |
}catch (IOException ie) { | |
System.out.println("uploadfile: problem executing HTTP request."+ ie); | |
}catch (Exception e) { | |
System.out.println("uploadfile: an error occurred." +e ); | |
} finally { | |
response.body().close(); | |
try{ | |
if(is !=null)is.close(); | |
}catch (IOException e){ | |
System.out.println("uploadfile: an error occurred." +e ); | |
} | |
} | |
return fileUploadID; | |
} |
HTTPCLIENT:
We can also use HTTP Client to write an api client to upload files to server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String uploadDocumentFilehttp(String sourceID,String accessToken, | |
String partID, String fileName) { | |
String fileUploadID = null; | |
try(CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { | |
byte fileData[] = Files.readAllBytes(Paths.get("C:\\Users\\lKadariya\\Desktop\\Test | |
\\DTtest\\TestFile\\original_testcases\\100\\100sample.pptx")); | |
String authorizationValue = "Bearer "+accessToken; | |
HttpEntity data = MultipartEntityBuilder.create() | |
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE) | |
.addBinaryBody("srcUploader",fileData,ContentType.DEFAULT_BINARY,fileName) | |
.build(); | |
HttpUriRequest request = RequestBuilder.post("https://"+HOST_TRANSPORT+ | |
"/api/files/upload") | |
.addHeader("Authorization",authorizationValue) | |
.addHeader("Accept","application/json") | |
.addParameter("filename",fileName) | |
.addParameter("targetFolderId",sourceID) | |
.setEntity(data) | |
.build(); | |
try(CloseableHttpResponse response = httpClient.execute(request);) { | |
int code = response.getStatusLine().getStatusCode(); | |
if (code != 200) { | |
HttpEntity entity = response.getEntity(); | |
ContentType contentType = ContentType.getOrDefault(entity); | |
Charset charset = contentType.getCharset(); | |
if (charset == null) { | |
charset = Charset.forName("UTF-8"); | |
} | |
String errorBody = EntityUtils.toString(entity, charset); | |
// log.info("uploadfile: Unable to process uploadfile. HTTP code: " + code + | |
" responseBody:"+errorBody);// | |
throw new PostEditException("uploadfile: Unable to process uploadfile. | |
HTTP code:" + code + " responseBody:"+errorBody); | |
} else { | |
HttpEntity entity = response.getEntity(); | |
ContentType contentType = ContentType.getOrDefault(entity); | |
Charset charset = contentType.getCharset(); | |
if (charset == null) { | |
charset = Charset.forName("UTF-8"); | |
} | |
String taggedResult = EntityUtils.toString(entity, charset); | |
Object json = new JSONTokener(taggedResult).nextValue(); | |
JSONObject jobj = null; | |
if(json instanceof JSONObject){ | |
jobj = (JSONObject)json ; | |
} else if(json instanceof JSONArray){ | |
jobj = (JSONObject)((JSONArray) json).getJSONObject(0); | |
} | |
Object error = jobj.getString("error"); | |
if (error == "null"){ | |
fileUploadID = (String)jobj.get("id"); | |
} | |
} | |
}catch (Exception e){ | |
// log.error("uploadfile: an error occurred in http execute." +e );// | |
throw new PostEditException("uploadfile: an error occurred http execute.", e); } | |
} catch (NoRouteToHostException re) { | |
// log.error("uploadfile: unable to route to host."+re);// | |
throw new PostEditException("uploadfile: unable to route to host.",re); | |
}catch (IOException ie) { | |
// log.error("uploadfile: problem executing HTTP request."+ ie);// | |
throw new PostEditException("uploadfile: problem executing HTTP request.",ie); | |
}catch (Exception e) { | |
// log.error("uploadfile: an error occurred." +e );// | |
throw new PostEditException("uploadfile: an error occurred.", e); } | |
return fileUploadID; | |
} |