org.apache.http.entity.mime.content.FileBody Java Examples

The following examples show how to use org.apache.http.entity.mime.content.FileBody. 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: HttpBodyPart.java    From ats-framework with Apache License 2.0 7 votes vote down vote up
ContentBody constructContentBody() throws UnsupportedEncodingException {

        ContentType contentTypeObject = constructContentTypeObject();

        if (filePath != null) { // FILE part
            if (contentTypeObject != null) {
                return new FileBody(new File(filePath), contentTypeObject);
            } else {
                return new FileBody(new File(filePath));
            }
        } else if (content != null) { // TEXT part
            if (contentTypeObject != null) {
                return new StringBody(content, contentTypeObject);
            } else {
                return new StringBody(content, ContentType.TEXT_PLAIN);
            }
        } else { // BYTE ARRAY part
            if (contentTypeObject != null) {
                return new ByteArrayBody(this.fileBytes, contentTypeObject, fileName);
            } else {
                return new ByteArrayBody(this.fileBytes, fileName);
            }
        }
    }
 
Example #2
Source File: RestSchedulerJobTaskTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testSubmit() throws Exception {
    String schedulerUrl = getResourceUrl("submit");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);
    File jobFile = RestFuncTHelper.getDefaultJobXmlfile();
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                                                                          .addPart("file",
                                                                                   new FileBody(jobFile,
                                                                                                ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    JSONObject jsonObj = toJsonObject(response);
    assertNotNull(jsonObj.get("id").toString());
}
 
Example #3
Source File: BibleUploader.java    From Quelea with GNU General Public License v3.0 6 votes vote down vote up
public void upload(File f) {
    new Thread() {
        public void run() {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addPart("file", new FileBody(f));

            HttpPost request = new HttpPost("http://quelea.org/bibleupload/upload.php");
            request.setEntity(builder.build());

            HttpClient client = HttpClients.createDefault();
            try {
                client.execute(request);
            } catch (IOException ex) {
                LOGGER.log(Level.WARNING, "Failed uploading bible", ex);
            }
        }
    }.start();
}
 
Example #4
Source File: AbstractStreamingAnalyticsService.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient,
        JsonObject service, File bundle, JsonObject jobConfigOverlay)
        throws IOException {

    String url = getJobSubmitUrl(httpClient, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addPart("bundle_file", bundleBody)
            .addPart("job_options", configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);

    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());

    return jsonResponse;
}
 
Example #5
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static void upload(URI uri, File src, String description) throws IOException {
   HttpPost httppost = new HttpPost(uri);
   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 #6
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 #7
Source File: TwoSharedUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void fileUpload() throws Exception {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(postURL);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //reqEntity.addPart("string_field",new StringBody("field value"));
        FileBody bin = new FileBody(new File("/home/vigneshwaran/VIGNESH/naruto.txt"));
        reqEntity.addPart("fff", bin);
        httppost.setEntity(reqEntity);
        System.out.println("Now uploading your file into 2shared.com. Please wait......................");
        HttpResponse response = httpclient.execute(httppost);
//        HttpEntity resEntity = response.getEntity();
//
//        if (resEntity != null) {
//            String page = EntityUtils.toString(resEntity);
//            System.out.println("PAGE :" + page);
//        }
    }
 
Example #8
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        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(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #9
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileUploadWithEagerParsing() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        //post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        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(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #10
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@Test
public void testFileUploadWithEagerParsingAndNonASCIIFilename() throws Exception {
    DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity();

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));

        File uploadfile = new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile());
        FormBodyPart filePart = new FormBodyPart("file", new FileBody(uploadfile, "τεστ", "application/octet-stream", Charsets.UTF_8.toString()));
        filePart.addField("Content-Disposition", "form-data; name=\"file\"; filename*=\"utf-8''%CF%84%CE%B5%CF%83%CF%84.txt\"");
        entity.addPart(filePart);

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);


    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #11
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 #12
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 #13
Source File: WuploadUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void fileUpload() throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    file = new File("/home/vigneshwaran/dinesh.txt");
    HttpPost httppost = new HttpPost(postURL);
    httppost.setHeader("Cookie", langcookie + ";" + sessioncookie + ";" + mailcookie + ";" + namecookie + ";" + rolecookie + ";" + orderbycookie + ";" + directioncookie + ";");
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file);
    mpEntity.addPart("files[]", cbFile);
    httppost.setEntity(mpEntity);
    System.out.println("Now uploading your file into wupload...........................");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    System.out.println(response.getStatusLine());
    if (response.getStatusLine().getStatusCode() == 302
            && response.getFirstHeader("Location").getValue().contains("upload/done/")) {

        System.out.println("Upload successful :)");
    } else {
        System.out.println("Upload failed :(");
    }

}
 
Example #14
Source File: SampleFileUpload.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Method that builds the multi-part form data request
 * @param urlString the urlString to which the file needs to be uploaded
 * @param file the actual file instance that needs to be uploaded
 * @param fileName name of the file, just to show how to add the usual form parameters
 * @param fileDescription some description for the file, just to show how to add the usual form parameters
 * @return server response as <code>String</code>
 */
public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {

    HttpPost postRequest = new HttpPost (urlString) ;
    try{

        MultipartEntity multiPartEntity = new MultipartEntity () ;

        //The usual form parameters can be added this way
        multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
        multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

        /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
        This part will be considered as file part and the rest of them as usual form-data parts*/
        FileBody fileBody = new FileBody(file, "application/octect-stream") ;
        multiPartEntity.addPart("attachment", fileBody) ;

        postRequest.setEntity(multiPartEntity) ;
    }catch (UnsupportedEncodingException ex){
        ex.printStackTrace() ;
    }

    return executeRequest (postRequest) ;
}
 
Example #15
Source File: DivShareUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
private static void fileUpload() throws Exception {

        file = new File("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\Sample Pictures\\Sunset.jpg");
        httpclient = new DefaultHttpClient();
//http://upload3.divshare.com/cgi-bin/upload.cgi?sid=8ef15852c69579ebb2db1175ce065ba6

        HttpPost httppost = new HttpPost(downURL + "cgi-bin/upload.cgi?sid=" + sid);


        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("file[0]", cbFile);

        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        System.out.println("Now uploading your file into divshare.com");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        System.out.println(EntityUtils.toString(resEntity));

    }
 
Example #16
Source File: TokenDemo.java    From ais-sdk with Apache License 2.0 6 votes vote down vote up
/**
    * 英文海关识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
    * @param token token认证串
    * @param formFile 文件路径
    * @throws IOException
    */
   public static void requestOcrCustomsFormEnBase64(String token, String formFile) {

       // 1.构建英文海关单据识别服务所需要的参数
	String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/action/ocr_form";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token) };
	try {
		MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
		multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		FileBody fileBody = new FileBody(new File(formFile), ContentType.create("image/jpeg", "utf-8"));
		multipartEntityBuilder.addPart("file", fileBody);

           // 2.传入英文海关单据识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
		HttpResponse response = HttpClientUtils.post(url, headers, multipartEntityBuilder.build());
		System.out.println(response);
		String content = IOUtils.toString(response.getEntity().getContent());
		System.out.println(content);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example #17
Source File: HttpQueryContext.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public byte[] doPost(String sessionId) {
//        FileEntity fe = new FileEntity();
//        StringEntity se = new StringEntity("","");
        try {
            FileBody fileBody = new FileBody(new File(""));
            StringBody stringBody = new StringBody("");
            HttpPost httpPost = new HttpPost("");
            MultipartEntityBuilder meb = MultipartEntityBuilder.create();
            meb.addPart("name", fileBody);
            meb.addPart("Sname",stringBody);
            HttpEntity httpEntity =  meb.build();
            httpPost.setEntity(httpEntity);
        }catch (Exception e){

        }
//        NameValuePair nameValuePair = new FileNa("","");
//        eb.setParameters()
//        HttpEntity httpEntity =  eb.build();
//        CloseableHttpPost httpPost = null;
//        httpPost.setEntity(httpEntity);
//        StringBody userName = new StringBody("Scott", ContentType.create(
//                                     "text/plain", Consts.UTF_8));
        return null;
    }
 
Example #18
Source File: PlainClientTest.java    From sumk with Apache License 2.0 6 votes vote down vote up
@Test
public void upload() throws IOException {
	String charset = "UTF-8";
	HttpClient client = HttpClientBuilder.create().build();
	String act = "upload";
	HttpPost post = new HttpPost(getUploadUrl(act));
	Map<String, Object> json = new HashMap<>();
	json.put("name", "张三");
	json.put("age", 23);
	String req = Base64.getEncoder().encodeToString(S.json().toJson(json).getBytes(charset));
	System.out.println("req:" + req);

	MultipartEntity reqEntity = new MultipartEntity();
	reqEntity.addPart("Api", StringBody.create("common", "text/plain", Charset.forName(charset)));
	reqEntity.addPart("data", StringBody.create(req, "text/plain", Charset.forName(charset)));
	reqEntity.addPart("img", new FileBody(new File("logo_bluce.jpg")));

	post.setEntity(reqEntity);
	HttpResponse resp = client.execute(post);
	String line = resp.getStatusLine().toString();
	Assert.assertEquals("HTTP/1.1 200 OK", line);
	HttpEntity resEntity = resp.getEntity();
	Log.get("upload").info(EntityUtils.toString(resEntity, charset));
}
 
Example #19
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
public String importImage(File file) throws IOException {
    if(getGalleryId() != null) {
        String url = getImportImageUrl();
        HttpGet get = new HttpGet(url);
        HttpResponse response = client.execute(get, context);
        this.cookies = response.getFirstHeader(Constant.SET_COOKIE_HEADER).getValue();

        // load file in form
        FileBody cbFile = new FileBody(file);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("physical", cbFile);
        builder.addPart("title", new StringBody("Image importée via ZestWriter", Charset.forName("UTF-8")));
        builder.addPart(Constant.CSRF_ZDS_KEY, new StringBody(getCookieValue(cookieStore, Constant.CSRF_COOKIE_KEY), ContentType.MULTIPART_FORM_DATA));

        Pair<Integer, String> resultPost = sendPost(url, builder.build());

        Document doc = Jsoup.parse(resultPost.getValue());
        Elements endPoints = doc.select("input[name=avatar_url]");
        if(!endPoints.isEmpty()) {
            return getBaseUrl() + endPoints.first().attr("value").trim();
        }
    }
    return "http://";
}
 
Example #20
Source File: HttpMimeParams.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
@Override
protected CloseableHttpResponse send(CloseableHttpClient httpClient, String baseUrl) throws Exception {
	//1)构建实体
	MultipartEntityBuilder entBuilder = MultipartEntityBuilder.create();		  
	for (String key : params.keySet()) {
		Object item = params.get(key);
		if(item instanceof File){
			File file = (File)item;
			if((!file.exists()) || (file.isDirectory())){
				throw new Exception("file error");
			}
			entBuilder.addPart(key, new FileBody(file));				
		}else if(item instanceof String){
			String value = (String)item;
			entBuilder.addPart(key, new StringBody(value, ContentType.TEXT_PLAIN));
		}else{
			throw new Exception(item.getClass().toString()+" not support");
		}
	}
	HttpEntity reqEntity = entBuilder.build();
	
	//2)发送并等待回复
	HttpPost request = new HttpPost(baseUrl);
	request.setEntity(reqEntity);
	return httpClient.execute(request);
}
 
Example #21
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParamWithFile() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    builder.addPart("form", fileBody);
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, file.getName());
}
 
Example #22
Source File: FileUploadClient.java    From nio-multipart with Apache License 2.0 6 votes vote down vote up
public  VerificationItems uploadFile(final File file, final Metadata metadata, final String endpoint, final String boundary){

        final HttpPost httpPost = new HttpPost(endpoint);
        final HttpEntity httpEntity;

        String metadataStr =  gson.toJson(metadata);

        if (log.isInfoEnabled()) {
            log.info("Metadata: " + metadataStr);
            log.info("File: " + file.getAbsolutePath());
        }

        httpEntity = MultipartEntityBuilder.create()
                .setBoundary(boundary)
                .addTextBody("metadata", metadataStr, ContentType.APPLICATION_JSON)
                .addPart(file.getName(), new FileBody(file))
                .build();

        httpPost.setEntity(httpEntity);

        return post(httpPost);
    }
 
Example #23
Source File: ZohoDocsUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\GeDotttUploaderPlugin.java");
        HttpPost httppost = new HttpPost("https://docs.zoho.com/uploadsingle.do?isUploadStatus=false&folderId=0&refFileElementId=refFileElement0");
        httppost.setHeader("Cookie", cookies.toString());
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("multiupload_file", cbFile);
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into zoho docs...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {

            String tmp = EntityUtils.toString(resEntity);
//            System.out.println(tmp);
            if(tmp.contains("File Uploaded Successfully"))
                System.out.println("File Uploaded Successfully");

        }
        //    uploadresponse = response.getLastHeader("Location").getValue();
        //  System.out.println("Upload response : " + uploadresponse);
    }
 
Example #24
Source File: HttpUploader.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
private URI uploadPackageAndGetURI(final CloseableHttpClient httpclient)
    throws IOException, URISyntaxException {
  File file = new File(this.topologyPackageLocation);
  String uploaderUri = HttpUploaderContext.getHeronUploaderHttpUri(this.config);
  post = new HttpPost(uploaderUri);
  FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
  builder.addPart(FILE, fileBody);
  HttpEntity entity = builder.build();
  post.setEntity(entity);
  HttpResponse response = execute(httpclient);
  String responseString = EntityUtils.toString(response.getEntity(),
      StandardCharsets.UTF_8.name());
  LOG.fine("Topology package download URI: " + responseString);

  return new URI(responseString);
}
 
Example #25
Source File: CrashReportTask.java    From archivo with GNU General Public License v3.0 6 votes vote down vote up
private void performUpload() {
    Path gzLog = compressLog();
    try (CloseableHttpClient client = buildHttpClient()) {
        HttpPost post = new HttpPost(CRASH_REPORT_URL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody logFile = new FileBody(gzLog.toFile(), ContentType.DEFAULT_BINARY);
        builder.addPart("log", logFile);
        StringBody uid = new StringBody(userId, ContentType.TEXT_PLAIN);
        builder.addPart("uid", uid);
        HttpEntity postEntity = builder.build();
        post.setEntity(postEntity);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.debug("Error uploading crash report: {}", response.getStatusLine());
        }
    } catch (IOException e) {
        logger.error("Error uploading crash report: {}", e.getLocalizedMessage());
    }
}
 
Example #26
Source File: RestSchedulerJobTaskTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testUrlMatrixParamsShouldReplaceJobVariables() throws Exception {
    File jobFile = new File(RestSchedulerJobTaskTest.class.getResource("config/job_matrix_params.xml").toURI());

    String schedulerUrl = getResourceUrl("submit;var=matrix_param_val");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    setSessionHeader(httpPost);

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create()
                                                                          .addPart("file",
                                                                                   new FileBody(jobFile,
                                                                                                ContentType.APPLICATION_XML));
    httpPost.setEntity(multipartEntityBuilder.build());

    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);
    JSONObject jsonObj = toJsonObject(response);
    final String jobId = jsonObj.get("id").toString();
    assertNotNull(jobId);

    waitJobState(jobId, JobStatus.FINISHED, TimeUnit.MINUTES.toMillis(1));
}
 
Example #27
Source File: HttpClientUtil.java    From ATest with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发送 post请求(带文件)
 * 
 * @param httpUrl
 *            地址
 * @param maps
 *            参数
 * @param fileLists
 *            附件
 */
public ResponseContent sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists,
		Map<String, String> headers, RequestConfig requestConfig, int executionCount, int retryInterval) {
	HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
	MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
	if (null != maps && maps.size() > 0) {
		for (String key : maps.keySet()) {
			meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
		}
	}
	for (File file : fileLists) {
		FileBody fileBody = new FileBody(file);
		meBuilder.addPart("files", fileBody);
	}
	HttpEntity reqEntity = meBuilder.build();
	httpPost.setEntity(reqEntity);
	return sendHttpPost(httpPost, headers, requestConfig, executionCount, retryInterval);
}
 
Example #28
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 #29
Source File: OronUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void fileUpload() throws IOException {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("H:\\Dinesh.java");
        HttpPost httppost = new HttpPost(oronlink);
        if (login) {

            httppost.setHeader("Cookie", logincookie + ";" + xfsscookie);
        }
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("upload_type", new StringBody("file"));
        mpEntity.addPart("srv_id", new StringBody(serverID));
        if (login) {
            mpEntity.addPart("sess_id", new StringBody(xfsscookie.substring(5)));
        }
        mpEntity.addPart("srv_tmp_url", new StringBody(tmpserver));
        mpEntity.addPart("file_0", cbFile);
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into oron...........................");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (resEntity != null) {

            String tmp = EntityUtils.toString(resEntity);
            System.out.println("Upload response : " + tmp);

            fnvalue = parseResponse(tmp, "name='fn' value='", "'");
            System.out.println("fn value : " + fnvalue);

        }
//        uploadresponse = response.getLastHeader("Location").getValue();
//        System.out.println("Upload response : " + uploadresponse);
    }
 
Example #30
Source File: FormControllerTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSingleFileUpload(@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 path = tempDir.resolve(UUID.randomUUID().toString());
       InputStream attachment = Resources.getResource("attachment.txt").openStream();
       Files.copy(attachment, path);
       multipartEntityBuilder.addPart("attachment", new FileBody(path.toFile()));
       HttpPost httpPost = new HttpPost("http://" + host + ":" + port + "/singlefile");
       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 attachment"));
}