org.apache.http.entity.mime.HttpMultipartMode Java Examples

The following examples show how to use org.apache.http.entity.mime.HttpMultipartMode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VideoSmsApi.java    From yunpian-java-sdk with MIT License 8 votes vote down vote up
/**
 * 
 * @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);
    }
}
 
Example #2
Source File: HttpClientPool.java    From message_interface with MIT License 7 votes vote down vote up
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();
    }
}
 
Example #3
Source File: ShareSendUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #4
Source File: ToutBox.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: MegaShareUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example #7
Source File: UploadBoxUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
 
Example #8
Source File: LoolFileConverter.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
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;
    }
 
Example #9
Source File: UGotFileUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
 
Example #10
Source File: ClassTest.java    From clouddisk with MIT License 6 votes vote down vote up
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();
    }
}
 
Example #11
Source File: MultiPartTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #12
Source File: MultiPartTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #13
Source File: TitanHttpPostProducer.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
    }
}
 
Example #14
Source File: UploadBox.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
 
Example #15
Source File: HttpService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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();
   }
}
 
Example #16
Source File: MediaImgUploadApacheHttpRequestExecutor.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@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();
  }
}
 
Example #17
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #18
Source File: EnterUploadUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
 
Example #19
Source File: FormControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example #20
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #21
Source File: BayFiles.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
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();
    }
 
Example #22
Source File: ZShareUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
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);
    }
 
Example #23
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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);
    }
}
 
Example #24
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #25
Source File: UploadActionListener.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
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();
	}
}
 
Example #26
Source File: MultiPartTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #27
Source File: IFile.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    try {
        //-------------------------------------------------------------


        if (iFileAccount.loginsuccessful) {
            host = iFileAccount.username + " | IFile.it";
        } else {
            host = "IFile.it";

            uploadInvalid();
            return;
        }

        if (file.length() > fileSizeLimit) {
            showWarningMessage( "<html><b>" + getClass().getSimpleName() + "</b> " + Translation.T().maxfilesize() + ": <b>1040MB</b></html>", getClass().getSimpleName());
            uploadInvalid();
            return;
        }
        uploadInitialising();

        NULogger.getLogger().info("Getting upload url from ifile.......");
        u = new URL("http://ifile.it/api-fetch_upload_url.api");
        uc = (HttpURLConnection) u.openConnection();

        br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String temp = "", k = "";
        while ((temp = br.readLine()) != null) {
            NULogger.getLogger().info(temp);
            k += temp;
        }

        uc.disconnect();
        postURL = StringUtils.stringBetweenTwoStrings(k, "upload_url\":\"", "\"");
        postURL = postURL.replaceAll("\\\\", "");
        NULogger.getLogger().log(Level.INFO, "Post URL : {0}", postURL);



        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(postURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("akey", new StringBody(properties().getEncryptedProperty("ifile_api_key")));
        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 ifile.it");
        uploading();
        HttpResponse response = httpclient.execute(httppost);
        gettingLink();
        NULogger.getLogger().info("Now getting downloading link.........");
        HttpEntity resEntity = response.getEntity();

        httpclient.getConnectionManager().shutdown();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (resEntity != null) {
            uploadresponse = EntityUtils.toString(resEntity);
            NULogger.getLogger().log(Level.INFO, "Upload response : {0}", uploadresponse);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try after some time :(");
        }

        if (uploadresponse.contains("\"status\":\"ok\"")) {
            NULogger.getLogger().info("File uploaded successfully :)");
            file_ukey = StringUtils.stringBetweenTwoStrings(uploadresponse, "\"ukey\":\"", "\"");
            NULogger.getLogger().log(Level.INFO, "File ukey : {0}", file_ukey);
            //http://ifile.it/6phxv2z

            downloadlink = "http://www.ifile.it/" + file_ukey + "/" + file.getName();
            downURL = downloadlink;
            NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try after some time :(");
        }


        NULogger.getLogger().log(Level.INFO, "Download Link: {0}", downURL);
        //NULogger.getLogger().log(Level.INFO, "Delete link: {0}", delURL);
        uploadFinished();
    } catch (Exception ex) {
        ex.printStackTrace();
        NULogger.getLogger().severe(ex.toString());
        uploadFailed();
    }
}
 
Example #28
Source File: NowDownload.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    try {
        if (nowDownloadAccount.loginsuccessful) {
            httpContext = nowDownloadAccount.getHttpContext();
            maxFileSizeLimit = 2147483648l; //2 GB
        } else {
            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();

        
        httpPost = new NUHttpPost(uploadURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("upload_key", new StringBody(upload_key));
        mpEntity.addPart("uid", new StringBody(uid));
        mpEntity.addPart("upload_server", new StringBody(upload_server));
        mpEntity.addPart("fileselect", createMonitoredFileBody());
        httpPost.setEntity(mpEntity);
        
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into NowDownload.to");
        uploading();
        httpResponse = httpclient.execute(httpPost, httpContext);
        responseString = EntityUtils.toString(httpResponse.getEntity());
        String up_session = StringUtils.stringBetweenTwoStrings(responseString, "\"session\":\"", "\"}");          
        String vid_url = "http://" + upload_server + "/upload.php?s=nowdownload&dd=nowdownload.to&upload_key=" + upload_key + "&uid=" + uid + "&session_id="+up_session;
        responseString = NUHttpClientUtils.getData(vid_url, httpContext);
        
        //Read the links
        gettingLink();
        downloadlink = "http://www.nowdownload.to/dl/"+StringUtils.stringBetweenTwoStrings(responseString, "video_id\":\"", "\"}");
        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();
    }
}
 
Example #29
Source File: XfileLoad.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    try {
        if (xfileLoadAccount.loginsuccessful) {
            userType = "reg";
            httpContext = xfileLoadAccount.getHttpContext();
            maxFileSizeLimit = 2097152000L; // 2,000 MB
        } else {
            userType = "anon";
            cookieStore = new BasicCookieStore();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            maxFileSizeLimit = 10485760; // 10 MB
        }

        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);
        
        uploadURL += uploadid_s + "&js_on=1&utype=" + userType + "&upload_type=file";
        // http://s1.xfileload.com/cgi-bin/upload.cgi?upload_id=024416275372&js_on=1&utype=reg&upload_type=file
        httpPost = new NUHttpPost(uploadURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("upload_type", new StringBody("file"));
        mpEntity.addPart("sess_id", new StringBody(sessionID));
        mpEntity.addPart("srv_tmp_url", new StringBody(srv_tmp_url));
        mpEntity.addPart("file_0", createMonitoredFileBody());
        mpEntity.addPart("file_0_descr", new StringBody(""));
        mpEntity.addPart("file_0_public", new StringBody("1"));
        mpEntity.addPart("link_rcpt", new StringBody(""));
        mpEntity.addPart("link_pass", new StringBody(""));
        mpEntity.addPart("to_folder", new StringBody(""));
        mpEntity.addPart("submit_btn", new StringBody("Start Upload"));
        httpPost.setEntity(mpEntity);
        
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into XfileLoad.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://xfileload.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();
    }
}
 
Example #30
Source File: Asfile.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    try {
        if (asfileAccount.loginsuccessful) {
            httpContext = asfileAccount.getHttpContext();
            sessionID = CookieUtils.getCookieValue(httpContext, "xfss");
            maxFileSizeLimit = 5368709120l; //5 GB
        } else {
            host = "Asfile.com";
            uploadInvalid();
            return;
        }

        if (file.length() > maxFileSizeLimit) {
            throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
        }
        uploadInitialising();
        initialize();

        
        httpPost = new NUHttpPost(uploadURL);
        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        mpEntity.addPart("MAX_FILE_SIZE", new StringBody("5497558138880"));
        mpEntity.addPart("token", new StringBody(token));
        mpEntity.addPart("agree", new StringBody("on"));
        mpEntity.addPart("tos", new StringBody("1"));
        mpEntity.addPart("file[]", createMonitoredFileBody());
        mpEntity.addPart("description[]", new StringBody(""));
        mpEntity.addPart("password[]", new StringBody(""));
        
        httpPost.setEntity(mpEntity);
        
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into Asfile.com");
        uploading();
        httpResponse = httpclient.execute(httpPost, httpContext);
        responseString = EntityUtils.toString(httpResponse.getEntity());
        
        //Read the links
        gettingLink();
        responseString = StringUtils.stringBetweenTwoStrings(responseString, "parent.upload_data = ", "parent.upload_done()");
        
        responseString = responseString.trim();
        responseString = StringUtils.removeLastChars(responseString, 2);
        responseString = StringUtils.removeFirstChar(responseString);
        
        final JSONObject jSonObject = new JSONObject(responseString);
        
        final String path = jSonObject.getString("path");
        
        downloadlink = "http://asfile.com/file/" + path;
        deletelink = "http://asfile.com/file/delete/" + path + "/" + jSonObject.getString("secret");
        
        //NULogger.getLogger().log(Level.INFO, "response : {0}", responseString);
        
        //FileUtils.saveInFile("Asfile.html", responseString);
        
        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();
    }
}