下面列出了怎么用org.apache.http.entity.mime.HttpMultipartMode的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@Ignore("UT3 - P3")
public void testMultiPartRequestToLarge() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/2";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("EXCEPTION: class java.lang.IllegalStateException", response);
} catch (IOException expected) {
//in some environments the forced close of the read side will cause a connection reset
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void testMultiPartIndividualFileToLarge() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/3";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("EXCEPTION: class java.lang.IllegalStateException", response);
} finally {
client.getConnectionManager().shutdown();
}
}
private void initialize() throws Exception {
responseString = NUHttpClientUtils.getData("http://toutbox.fr/", httpContext);
doc = Jsoup.parse(responseString);
accNo = doc.select("input[name=__accno]").attr("value");
httpPost = new NUHttpPost("http://toutbox.fr/action/Upload/GetUrl/");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("accountId", new StringBody(accNo));
mpEntity.addPart("folderId", new StringBody("0"));
mpEntity.addPart("__RequestVerificationToken", new StringBody("undefined"));
httpPost.setEntity(mpEntity);
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
JSONObject jSon = new JSONObject(responseString);
uploadURL = jSon.getString("Url") + "&ms=" + System.currentTimeMillis();
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("emai", new StringBody("Free"));
mpEntity.addPart("upload_range", new StringBody("1"));
mpEntity.addPart("upfile_0", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into MegaShare.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
uploadresponse = response.getLastHeader("Location").getValue();
System.out.println("Upload response : "+uploadresponse);
System.out.println(response.getStatusLine());
httpclient.getConnectionManager().shutdown();
}
/**
*
* @param param
* apikey sign
* @param layout
* {@code VideoLayout}
* @param material
* 视频资料zip文件
*
* @return
*/
public Result<Template> addTpl(Map<String, String> param, String layout, byte[] material) {
Result<Template> r = new Result<>();
if (layout == null || material == null) return r.setCode(Code.ARGUMENT_MISSING);
List<NameValuePair> list = param2pair(param, r, APIKEY, SIGN);
if (r.getCode() != Code.OK) return r;
Charset ch = Charset.forName(charset());
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(ch).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for (NameValuePair pair : list) {
builder.addTextBody(pair.getName(), pair.getValue(), ContentType.create("text/plain", ch));
}
builder.addTextBody(LAYOUT, layout, ContentType.APPLICATION_JSON);
builder.addBinaryBody(MATERIAL, material, ContentType.create("application/octet-stream", ch), null);
StdResultHandler<Template> h = new StdResultHandler<>(new TypeToken<Result<Template>>() {}.getType());
try {
return path("add_tpl.json").post(new HttpEntityWrapper(builder.build()), h, r);
} catch (Exception e) {
return h.catchExceptoin(e, r);
}
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
httppost.setHeader("Cookie", sidcookie);
file = new File("h:/install.txt");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("filepc", cbFile);
mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into uploadbox.com");
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
uploadresponse = response.getLastHeader("Location").getValue();
uploadresponse = getData(uploadresponse);
downloadlink = parseResponse(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
deletelink = parseResponse(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
System.out.println("Download link " + downloadlink);
System.out.println("deletelink : " + deletelink);
}
public static void main(String args[]){
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/sso-web/upload");
httpPost.addHeader("Range","bytes=10000-");
final MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setCharset(Consts.UTF_8);
multipartEntity.setMode(HttpMultipartMode.STRICT);
multipartEntity.addBinaryBody("file", new File("/Users/huanghuanlai/Desktop/test.java"));
httpPost.setEntity(multipartEntity.build());
try {
HttpResponse response = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
}
public String uploadFile(String url, String path) throws IOException {
HttpPost post = new HttpPost(url);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(path)); //image should be a String
builder.addPart("file", fileBody);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
return readResponse(response);
} finally {
post.releaseConnection();
}
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/Sakura haruno.jpg");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
// mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into ugotfile.com");
HttpResponse response = httpclient.execute(httppost);
System.out.println(response.getStatusLine());
if (response != null) {
uploadresponse = EntityUtils.toString(response.getEntity());
}
System.out.println("Upload Response : " + uploadresponse);
downloadlink = parseResponse(uploadresponse, "[\"", "\"");
downloadlink = downloadlink.replaceAll("\\\\/", "/");
deletelink = parseResponse(uploadresponse, "\",\"", "\"");
deletelink = deletelink.replaceAll("\\\\/", "/");
System.out.println("Download Link : " + downloadlink);
System.out.println("Delete Link : " + deletelink);
}
public static byte[] convert(String baseUrl, InputStream sourceInputStream) throws IOException {
int timeoutMillis = 5000;
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.setSocketTimeout(timeoutMillis * 1000).build();
CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpPost httpPost = new HttpPost(baseUrl + "/lool/convert-to/pdf");
HttpEntity multipart = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("data", sourceInputStream, ContentType.MULTIPART_FORM_DATA, "anything")
.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = client.execute(httpPost);
byte[] convertedFileBytes = EntityUtils.toByteArray(response.getEntity());
client.close();
return convertedFileBytes;
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/install.txt");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("Filename", new StringBody(file.getName()));
mpEntity.addPart("Filedata", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into sharesend.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
System.out.println("Upload Response : " + uploadresponse);
System.out.println("Download Link : http://sharesend.com/" + uploadresponse);
httpclient.getConnectionManager().shutdown();
}
@Test
public void testAuthorizationFailed() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString("123:123".getBytes()));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(403, response.getStatusLine().getStatusCode());
String error = TestUtil.consumeText(response);
assertNotNull(error);
assertEquals("Authentication failed.", error);
}
}
@Test
public void testMultiPartRequest() throws IOException {
TestHttpClient client = new TestHttpClient();
try {
String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1";
HttpPost post = new HttpPost(uri);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
final String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("PARAMS:\n" +
"name: formValue\n" +
"filename: null\n" +
"content-type: null\n" +
"Content-Disposition: form-data; name=\"formValue\"\n" +
"size: 7\n" +
"content: myValue\n" +
"name: file\n" +
"filename: uploadfile.txt\n" +
"content-type: application/octet-stream\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n" +
"Content-Type: application/octet-stream\n" +
"size: 13\n" +
"content: file contents\n", response);
} finally {
client.getConnectionManager().shutdown();
}
}
@Test
public void testFileUploadWithMediumFileSizeThresholdAndLargeFile() throws Exception {
int fileSizeThreshold = 1000;
DefaultServer.setRootHandler(new BlockingHandler(createInMemoryReadingHandler(fileSizeThreshold)));
TestHttpClient client = new TestHttpClient();
File file = new File("tmp_upload_file.txt");
file.createNewFile();
try {
writeLargeFileContent(file, fileSizeThreshold * 2);
HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
entity.addPart("file", new FileBody(file));
post.setEntity(entity);
HttpResponse result = client.execute(post);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
String resp = HttpClientUtils.readResponse(result);
Map<String, String> parsedResponse = parse(resp);
Assert.assertEquals("false", parsedResponse.get("in_memory"));
Assert.assertEquals("tmp_upload_file.txt", parsedResponse.get("file_name"));
Assert.assertEquals(DigestUtils.md5Hex(new FileInputStream(file)), parsedResponse.get("hash"));
} finally {
file.delete();
client.getConnectionManager().shutdown();
}
}
public static void upload(URI uri, Credentials auth, File src, String description) throws IOException {
String cred = auth.getUserPrincipal().getName()+":"+auth.getPassword();
String encoding = Base64.encodeBase64String(cred.getBytes());
HttpPost httppost = new HttpPost(uri);
// Add in authentication
httppost.setHeader("Authorization", "Basic " + encoding);
FileBody data = new FileBody(src);
StringBody text = new StringBody(description, ContentType.TEXT_PLAIN);
// Build up multi-part form
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("upload", data)
.addPart("comment", text)
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.build();
httppost.setEntity(reqEntity);
// Execute post and get response
CloseableHttpClient client = get();
CloseableHttpResponse response = client.execute(httppost);
try {
HttpEntity resEntity = response.getEntity();
EntityUtils.consume(resEntity);
} finally {
response.close();
}
}
@Override
public WxMediaImgUploadResult execute(String uri, File data) throws WxErrorException, IOException {
if (data == null) {
throw new WxErrorException(WxError.builder().errorCode(-1).errorMsg("文件对象为空").build());
}
HttpPost httpPost = new HttpPost(uri);
if (requestHttp.getRequestHttpProxy() != null) {
RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
httpPost.setConfig(config);
}
HttpEntity entity = MultipartEntityBuilder
.create()
.addBinaryBody("media", data)
.setMode(HttpMultipartMode.RFC6532)
.build();
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpPost)) {
String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
WxError error = WxError.fromJson(responseContent, WxType.MP);
if (error.getErrorCode() != 0) {
throw new WxErrorException(error);
}
return WxMediaImgUploadResult.fromJson(responseContent);
} finally {
httpPost.releaseConnection();
}
}
private void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
if (uploadBoxAccount.loginsuccessful) {
httppost.setHeader("Cookie", UploadBoxAccount.getSidcookie());
} else {
httppost.setHeader("Cookie", sidcookie);
}
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("filepc", createMonitoredFileBody());
mpEntity.addPart("server", new StringBody(server));
httppost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into uploadbox.com");
uploading();
HttpResponse response = httpclient.execute(httppost);
gettingLink();
NULogger.getLogger().info(response.getStatusLine().toString());
uploadresponse = response.getLastHeader("Location").getValue();
NULogger.getLogger().log(Level.INFO, "Upload Response : {0}", uploadresponse);
uploadresponse = getData(uploadresponse);
downloadlink = StringUtils.stringBetweenTwoStrings(uploadresponse, "name=\"loadlink\" id=\"loadlink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
deletelink = StringUtils.stringBetweenTwoStrings(uploadresponse, "name=\"deletelink\" id=\"deletelink\" class=\"text\" onclick=\"this.select();\" value=\"", "\"");
downURL = downloadlink;
delURL = deletelink;
NULogger.getLogger().log(Level.INFO, "Download link {0}", downloadlink);
NULogger.getLogger().log(Level.INFO, "deletelink : {0}", deletelink);
uploadFinished();
}
private static void fileUpload() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(postURL);
file = new File("h:/UploadingdotcomUploaderPlugin.java");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("upload_type", new StringBody("file"));
mpEntity.addPart("sess_id", new StringBody(sessid));
mpEntity.addPart("srv_tmp_url", new StringBody(servertmpurl));
mpEntity.addPart("file_0", cbFile);
mpEntity.addPart("submit_btn", new StringBody(" Upload!"));
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into enterupload.com");
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// uploadresponse = response.getLastHeader("Location").getValue();
// System.out.println("Upload response : " + response.toString());
System.out.println(response.getStatusLine());
if (resEntity != null) {
uploadresponse = EntityUtils.toString(resEntity);
}
// if (resEntity != null) {
// resEntity.consumeContent();
// }
downloadid = parseResponse(uploadresponse, "<textarea name='fn'>", "<");
httpclient.getConnectionManager().shutdown();
}
private void fileUpload() throws Exception {
HttpPost httpPost = new HttpPost(postURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("file", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
uploading();
NULogger.getLogger().info("Now uploading your file into bayfiles.com");
HttpResponse response = httpclient.execute(httpPost);
gettingLink();
uploadresponse = EntityUtils.toString(response.getEntity());
NULogger.getLogger().info(response.getStatusLine().toString());
//
// NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse);
jSonOjbject = new JSONObject(uploadresponse);
downloadlink = jSonOjbject.getString("downloadUrl");
deletelink = jSonOjbject.getString("deleteUrl");
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
downURL = downloadlink;
delURL = deletelink;
uploadFinished();
}
/**
* Posts JSON to a URL
* @param transmissionString
*/
private void publish(String transmissionString)
{
try
{
String iotype = "json";
String fieldName = "json";
String contentType = "application/json";
// String fileName = "filename.graphson";
// upload a GraphSON file
HttpPost httpPost = new HttpPost(apiURL + "/titan");
// byte[] userpass = (userId + ":" + password).getBytes();
// byte[] encoding = Base64.encodeBase64(userpass);
/// httpPost.setHeader("Authorization", "Basic " + new String(encoding));
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meb.addPart("fieldName", new StringBody(fieldName));
meb.addPart("contentType", new StringBody(contentType));
// meb.addPart("name", new StringBody(fileName));
meb.addTextBody("transaction", transmissionString);
// FileBody fileBody = new FileBody(new File("./data/" + fileName));
// meb.addPart(fieldName, fileBody);
httpPost.setEntity(meb.build());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// EntityUtils.consume(httpEntity);
String responseString = EntityUtils.toString(httpEntity, "UTF-8");
System.out.println(responseString);
} catch (Exception e)
{
e.printStackTrace();
}
}
private static HttpResponse sendData(
CloseableHttpClient client,
File reportFile,
String serverUrl,
String apiKey,
String project
) throws IOException{
if(client == null)
return null;
try {
HttpPost post = new HttpPost(serverUrl + "/api/projects/" + project + "/analysis");
post.setHeader("API-Key", apiKey);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", new FileBody(reportFile));
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
EntityUtils.consume(resEntity);
}
return response;
} finally {
client.close();
}
}
@Test
public void testImprovedUploadMethod() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
String path;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
path = TestUtil.consumeText(response);
assertNotNull(path);
assertTrue(path.startsWith("/static"));
assertTrue(path.endsWith("bin"));
}
String responseUrl = "http://127.0.0.1:18080" + path;
verify(clientPair.hardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);
try (CloseableHttpResponse response = httpclient.execute(index)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
}
}
@Test
public void testOTAFailedWhenNoDevice() throws Exception {
clientPair.hardwareClient.stop();
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + clientPair.token);
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(400, response.getStatusLine().getStatusCode());
String error = TestUtil.consumeText(response);
assertNotNull(error);
assertEquals("No device in session.", error);
}
}
private static void getDownloadLink() throws Exception {
// Note : If the response header contains redirection.i.e 302 Found and moved,use the below code to get that moved page
System.out.println("Now Getting Download link...");
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(zsharedomain);
if (login) {
httppost.setHeader("Cookie", xfsscookie);
}
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("fn", new StringBody(fnvalue));
mpEntity.addPart("op", new StringBody("upload_result"));
mpEntity.addPart("st", new StringBody("OK"));
httppost.setEntity(mpEntity);
// h.setHeader("Referer", postURL);
// h.setHeader("Cookie", sidcookie + ";" + mysessioncookie);
HttpResponse res = client.execute(httppost);
HttpEntity entity = res.getEntity();
linkpage = EntityUtils.toString(entity);
System.out.println(linkpage);
downloadlink = parseResponse(linkpage, "Direct Link:</b></td>", "</td>");
downloadlink = parseResponse(downloadlink, "value=\"", "\"");
deletelink = parseResponse(linkpage, "Delete Link:</b></td>", "</td>");
deletelink = parseResponse(deletelink, "value=\"", "\"");
System.out.println("Download link : " + downloadlink);
System.out.println("Delete Link : " + deletelink);
}
@Test
public void basicOTAForAllDevices() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start");
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
String path;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
path = TestUtil.consumeText(response);
assertNotNull(path);
assertTrue(path.startsWith("/static"));
assertTrue(path.endsWith("bin"));
}
String responseUrl = "http://127.0.0.1:18080" + path;
verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
HttpGet index = new HttpGet("http://localhost:" + properties.getHttpPort() + path);
try (CloseableHttpResponse response = httpclient.execute(index)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("application/octet-stream", response.getHeaders("Content-Type")[0].getValue());
}
}
@Test
public void testMultiFileUpload(@TempDir Path tempDir) throws IOException {
// given
String host = Application.getInstance(Config.class).getConnectorHttpHost();
int port = Application.getInstance(Config.class).getConnectorHttpPort();
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// when
Path path1 = tempDir.resolve(UUID.randomUUID().toString());
Path path2 = tempDir.resolve(UUID.randomUUID().toString());
InputStream attachment1 = Resources.getResource("attachment.txt").openStream();
InputStream attachment2 = Resources.getResource("attachment.txt").openStream();
Files.copy(attachment1, path1);
Files.copy(attachment2, path2);
multipartEntityBuilder.addPart("attachment1", new FileBody(path1.toFile()));
multipartEntityBuilder.addPart("attachment2", new FileBody(path2.toFile()));
HttpPost httpPost = new HttpPost("http://" + host + ":" + port + "/multifile");
httpPost.setEntity(multipartEntityBuilder.build());
String response = null;
HttpResponse httpResponse = httpClientBuilder.build().execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity);
}
// then
assertThat(httpResponse, not(nullValue()));
assertThat(response, not(nullValue()));
assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(StatusCodes.OK));
assertThat(response, equalTo("This is an attachmentThis is an attachment2"));
}
@Override
public void run() {
try {
if (sharedAccount.loginsuccessful) {
userType = "reg";
httpContext = sharedAccount.getHttpContext();
//sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
maxFileSizeLimit = 1073741824L; // 1 GB
}
else {
host = "Shared.com";
uploadInvalid();
return;
}
if (file.length() > maxFileSizeLimit) {
throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
}
uploadInitialising();
initialize();
httpPost = new NUHttpPost("http://shared.com/upload/process");
httpPost.setHeader("Host", "shared.com");
httpPost.setHeader("Referer", sharedAccount.member_upload_url);
httpPost.setHeader("Accept", "application/json, text/javascript, */*;");
httpPost.setHeader("X-CSRF-TOKEN", authenticity_token);
httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("files[]", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into Shared.com");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
if (responseString.isEmpty()){
uploadFailed();
}
//Read the links
gettingLink();
downloadlink = StringUtils.stringBetweenTwoStrings(responseString, "\"url\":\"", "\"");
deletelink = UploadStatus.NA.getLocaleSpecificString();
NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
downURL = downloadlink;
delURL = deletelink;
uploadFinished();
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
@Override
public void run() {
try {
if (keepTwoShareAccount.loginsuccessful) {
httpContext = keepTwoShareAccount.getHttpContext();
maxFileSizeLimit = 5242880000l; //5000 MB
} else {
host = "Keep2Share.cc";
uploadInvalid();
return;
}
if (file.length() > maxFileSizeLimit) {
throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), keepTwoShareAccount.getHOSTNAME());
}
uploadInitialising();
initialize();
httpPost = new NUHttpPost(uploadURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("catalog", new StringBody(catalog));
mpEntity.addPart("userId", new StringBody(Integer.toString(userId)));
mpEntity.addPart("expires", new StringBody(Long.toString(expires)));
mpEntity.addPart("hmac", new StringBody(hmac));
mpEntity.addPart("projectName", new StringBody("k2s"));
mpEntity.addPart("ajax", new StringBody(Boolean.toString(ajax)));
mpEntity.addPart("qquuid", new StringBody(qquuid));
mpEntity.addPart("qqtotalfilesize", new StringBody(Long.toString(file.length())));
mpEntity.addPart("Filedata", createMonitoredFileBody());
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into Keep2Share.cc");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
//FileUtils.saveInFile("KeepTwoShare.html", responseString);
jSonObject = new JSONObject(responseString);
if(jSonObject.has("success") && jSonObject.getBoolean("success")){
doc = Jsoup.parse(responseString);
//Read the links
gettingLink();
responseString = NUHttpClientUtils.getData("http://keep2share.cc/files.html", httpContext);
doc = Jsoup.parse(responseString);
Elements aElements = doc.select("div#content div#file-manager.file-manager table.items tbody tr.file td.name a");
boolean found = false;
//Find the file name
for(Element aElement : aElements){
if(!found && aElement.text().equals(file.getName())){
responseString = NUHttpClientUtils.getData("http://keep2share.cc" + aElement.attr("href"), httpContext);
doc = Jsoup.parse(responseString);
downloadlink = doc.select("textarea").first().text();
found = true;
}
}
if(found){
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
downURL = downloadlink;
}
else{
throw new Exception("Download and delete link not found!");
}
}
else{
throw new Exception("Upload error: " + responseString);
}
uploadFinished();
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}
private MultipartEntity createMultiPartFormPostEntity() throws IOException {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("foo", new StringBody("bar"));
return entity;
}
@Override
public void run() {
try {
if (useFileAccount.loginsuccessful) {
userType = "reg";
httpContext = useFileAccount.getHttpContext();
sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
maxFileSizeLimit = 4294967296L; // 4 GB
} else {
userType = "anon";
cookieStore = new BasicCookieStore();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
maxFileSizeLimit = 2147483648L; // 2 GB
}
if (file.length() > maxFileSizeLimit) {
throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
}
uploadInitialising();
initialize();
long uploadID;
Random random = new Random();
uploadID = Math.round(random.nextFloat() * Math.pow(10,12));
uploadid_s = String.valueOf(uploadID);
sess_id = StringUtils.stringBetweenTwoStrings(responseString, "name=\"sess_id\" value=\"", "\"");
srv_tmp_url = uploadURL;
uploadURL = StringUtils.removeLastChars(uploadURL, 3) + "cgi-bin/upload.cgi?upload_id=" + uploadid_s + "&js_on=1&utype=" + userType + "&upload_type=file";
httpPost = new NUHttpPost(uploadURL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.addPart("js_on", new StringBody("1"));
mpEntity.addPart("upload_id", new StringBody(uploadid_s));
mpEntity.addPart("upload_type", new StringBody("file"));
mpEntity.addPart("utype", new StringBody(userType));
mpEntity.addPart("sess_id", new StringBody(sess_id));
mpEntity.addPart("srv_tmp_url", new StringBody(srv_tmp_url));
mpEntity.addPart("file_0", createMonitoredFileBody());
mpEntity.addPart("file_1", new StringBody(""));
mpEntity.addPart("file_0_descr", new StringBody(""));
mpEntity.addPart("file_0_public", new StringBody("1"));
mpEntity.addPart("submit_btn", new StringBody("Upload"));
mpEntity.addPart("tos", new StringBody("1"));
httpPost.setEntity(mpEntity);
NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
NULogger.getLogger().info("Now uploading your file into UseFile.com");
uploading();
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
//Read the links
gettingLink();
upload_fn = doc.select("textarea[name=fn]").val();
if (upload_fn != null) {
httpPost = new NUHttpPost("http://usefile.com");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("fn", upload_fn));
formparams.add(new BasicNameValuePair("op", "upload_result"));
formparams.add(new BasicNameValuePair("st", "OK"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httpPost.setEntity(entity);
httpResponse = httpclient.execute(httpPost, httpContext);
responseString = EntityUtils.toString(httpResponse.getEntity());
doc = Jsoup.parse(responseString);
downloadlink = doc.select("textarea").first().val();
deletelink = doc.select("textarea").eq(3).val();
NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
downURL = downloadlink;
delURL = deletelink;
uploadFinished();
}
} catch(NUException ex){
ex.printError();
uploadInvalid();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);
uploadFailed();
}
}