List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:org.eclipse.cbi.maven.plugins.winsigner.SignMojo.java
/** * helper to send the file to the signing service * @param source file to send//from w w w. j a v a 2 s .c o m * @param target file to copy response to * @throws IOException * @throws MojoExecutionException */ private void postFile(File source, File target) throws IOException, MojoExecutionException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(signerUrl); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(source)); post.setEntity(reqEntity); HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); if (statusCode >= 200 && statusCode <= 299 && resEntity != null) { InputStream is = resEntity.getContent(); try { FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target); } finally { IOUtil.close(is); } } else { throw new MojoExecutionException("Signer replied " + response.getStatusLine()); } }
From source file:li.zeitgeist.api.ZeitgeistApi.java
public List<Item> createByFiles(List<File> files, String tags, boolean announce, OnProgressListener listener) throws ZeitgeistError { MultipartEntity entity;//from w ww. ja v a2s.c o m if (listener == null) { entity = new MultipartEntity(); } else { entity = new MultipartEntityWithProgress(listener); } for (File file : files) { entity.addPart("image_upload[]", new FileBody(file)); } try { entity.addPart("tags", new StringBody(tags)); entity.addPart("announce", new StringBody(announce ? "true" : "false")); } catch (UnsupportedEncodingException e) { throw new ZeitgeistError("UnsupportedEncoding: " + e.getMessage()); } Map<String, ?> jsonObject = postRequest("/new", entity); ArrayList<Map<String, ?>> itemObjects = (ArrayList<Map<String, ?>>) jsonObject.get("items"); List<Item> items = new Vector<Item>(); for (Map<String, ?> itemObject : itemObjects) { items.add(new Item(itemObject, baseUrl)); } return items; }
From source file:org.r10r.doctester.testbrowser.TestBrowserImpl.java
private Response makePatchPostOrPutRequest(Request httpRequest) { org.apache.http.HttpResponse apacheHttpClientResponse; Response response = null;/*from www . j a va2 s .c om*/ try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpEntityEnclosingRequestBase apacheHttpRequest; if (PATCH.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPatch(httpRequest.uri); } else if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPost(httpRequest.uri); } else { apacheHttpRequest = new HttpPut(httpRequest.uri); } if (httpRequest.headers != null) { // add all headers for (Entry<String, String> header : httpRequest.headers.entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } /////////////////////////////////////////////////////////////////// // Either add form parameters... /////////////////////////////////////////////////////////////////// if (httpRequest.formParameters != null) { List<BasicNameValuePair> formparams = Lists.newArrayList(); for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add multipart file upload /////////////////////////////////////////////////////////////////// if (httpRequest.filesToUpload != null) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) { // For File parameters entity.addPart(entry.getKey(), new FileBody((File) entry.getValue())); } apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add payload and convert if Json or Xml /////////////////////////////////////////////////////////////////// if (httpRequest.payload != null) { if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) { String string = new ObjectMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType("application/json; charset=utf-8"); apacheHttpRequest.setEntity(entity); } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) { String string = new XmlMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8); apacheHttpRequest.setEntity(new StringEntity(string, "utf-8")); } else if (httpRequest.payload instanceof String) { StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8"); apacheHttpRequest.setEntity(entity); } else { StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8"); apacheHttpRequest.setEntity(entity); } } setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects); // Here we go! apacheHttpClientResponse = httpClient.execute(apacheHttpRequest); response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse); apacheHttpRequest.releaseConnection(); } catch (IOException e) { logger.error("Fatal problem creating PATCH, POST or PUT request in TestBrowser", e); throw new RuntimeException(e); } return response; }
From source file:com.ibm.watson.developer_cloud.dialog.v1.DialogService.java
/** * Creates a dialog./* ww w . ja v a 2 s. c o m*/ * * @param name The dialog name * @param dialogFile The dialog file created by using the Dialog service Applet. * @return The created dialog * @see Dialog */ public Dialog createDialog(final String name, final File dialogFile) { if (name == null || name.isEmpty()) throw new IllegalArgumentException("name can not be null or empty"); if (dialogFile == null || !dialogFile.exists()) throw new IllegalArgumentException("dialogFile can not be null or empty"); try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(dialogFile)); reqEntity.addPart("name", new StringBody(name, Charset.forName("UTF-8"))); HttpRequestBase request = Request.Post("/v1/dialogs").withEntity(reqEntity).build(); /*HttpHost proxy=new HttpHost("10.100.1.124",3128); ConnRouteParams.setDefaultProxy(request.getParams(),proxy);*/ HttpResponse response = execute(request); return ResponseUtil.getObject(response, Dialog.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.alibaba.openapi.client.rpc.AbstractHttpRequestBuilder.java
public HttpRequest getHttpRequest(InvokeContext context) { final RequestPolicy requestPolicy = context.getPolicy(); final StringBuilder path = getProtocolRequestPath(context, getProtocol()); final StringBuilder queryString = new StringBuilder(); final String method; final List<NameValuePair> parameters = buildParams(context); buildSysParams(parameters, queryString, context, requestPolicy); HttpEntity entity = null;/*w w w . j ava 2 s . c o m*/ switch (requestPolicy.getHttpMethod()) { case POST: method = METHOD_POST; break; case GET: method = METHOD_GET; break; case AUTO: if (hasParameters(parameters) || hasAttachments(context.getRequest())) { method = METHOD_POST; } else { method = METHOD_GET; } break; default: method = METHOD_POST; } if (hasParameters(parameters)) { if (METHOD_GET.equals(method)) { if (queryString.length() > 0) { queryString.append(PARAMETER_SEPARATOR); } queryString.append(URLEncodedUtils.format(parameters, requestPolicy.getQueryStringCharset())); } else { try { entity = new UrlEncodedFormEntity(parameters, requestPolicy.getContentCharset()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } } signature(path, queryString, parameters, requestPolicy); HttpRequest httpRequest; try { httpRequest = requestFactory.newHttpRequest(method, getApiRequestPath(context, requestPolicy) .append('/').append(path).append(QUERY_STRING_SEPARATOR).append(queryString).toString()); } catch (MethodNotSupportedException e) { throw new UnsupportedOperationException("Unsupported http request method:" + e.getMessage(), e); } if (httpRequest instanceof BasicHttpEntityEnclosingRequest) { if (hasAttachments(context.getRequest())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Entry<String, String> entry : context.getRequest().getAttachments().entrySet()) { File file = new File(entry.getValue()); multipartEntity.addPart(entry.getKey(), new FileBody(file)); } entity = multipartEntity; } else if (requestPolicy.getRequestCompressThreshold() >= 0 && entity.getContentLength() > requestPolicy.getRequestCompressThreshold()) { entity = new GzipCompressingNEntity(entity); httpRequest.addHeader("Content-Encoding", "gzip"); } ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity); } // httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // httpRequest.addHeader("Accept-Charset", "gb18030,utf-8;q=0.7,*;q=0.3"); // httpRequest.addHeader("Accept-Encoding", "gzip,deflate,sdch"); // httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.8"); // httpRequest.addHeader("Cache-Control", "max-age=0"); // httpRequest.addHeader("Connection", "keep-alive"); return httpRequest; }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequestToLarge() throws IOException { TestHttpClient client = new TestHttpClient(); try {/*from ww w .j av a 2 s .c om*/ 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); Assert.assertEquals(DefaultServer.isH2() || DefaultServer.isAjp() ? StatusCodes.SERVICE_UNAVAILABLE : StatusCodes.INTERNAL_SERVER_ERROR, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } catch (IOException expected) { //in some environments the forced close of the read side will cause a connection reset } finally { client.getConnectionManager().shutdown(); } }
From source file:org.openml.knime.OpenMLWebservice.java
/** * Upload a run./* w w w . j av a2 s . co m*/ * * @param description Description to the run * @param files Run files * @param user Name of the user * @param password Password of the user * @return Response from the server * @throws Exception */ public static String sendRuns(final File description, final File[] files, final String user, final String password) throws Exception { String result = ""; DefaultHttpClient httpclient = new DefaultHttpClient(); Credentials credentials = new UsernamePasswordCredentials(user, password); AuthScope scope = new AuthScope(new URI(WEBSERVICEURL).getHost(), 80); httpclient.getCredentialsProvider().setCredentials(scope, credentials); try { String url = WEBSERVICEURL + "?f=openml.run.upload"; HttpPost httppost = new HttpPost(url); MultipartEntity reqEntity = new MultipartEntity(); FileBody descriptionBin = new FileBody(description); reqEntity.addPart("description", descriptionBin); for (int i = 0; i < files.length; i++) { FileBody bin = new FileBody(files[i]); reqEntity.addPart("predictions", bin); } httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() < 200) { throw new Exception(response.getStatusLine().getReasonPhrase()); } if (resEntity != null) { result = convertStreamToString(resEntity.getContent()); } ErrorDocument errorDoc = null; try { errorDoc = ErrorDocument.Factory.parse(result); } catch (Exception e) { // no error XML should mean no error } if (errorDoc != null && errorDoc.validate()) { ErrorDocument.Error error = errorDoc.getError(); String errorMessage = error.getCode() + " : " + error.getMessage(); if (error.isSetAdditionalInformation()) { errorMessage += " : " + error.getAdditionalInformation(); } throw new Exception(errorMessage); } EntityUtils.consume(resEntity); } finally { try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) { // ignore } } return result; }
From source file:org.doctester.testbrowser.TestBrowserImpl.java
private Response makePostOrPutRequest(Request httpRequest) { org.apache.http.HttpResponse apacheHttpClientResponse; Response response = null;/*from w ww . ja v a2 s. c o m*/ try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpEntityEnclosingRequestBase apacheHttpRequest; if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) { apacheHttpRequest = new HttpPost(httpRequest.uri); } else { apacheHttpRequest = new HttpPut(httpRequest.uri); } if (httpRequest.headers != null) { // add all headers for (Entry<String, String> header : httpRequest.headers.entrySet()) { apacheHttpRequest.addHeader(header.getKey(), header.getValue()); } } /////////////////////////////////////////////////////////////////// // Either add form parameters... /////////////////////////////////////////////////////////////////// if (httpRequest.formParameters != null) { List<BasicNameValuePair> formparams = Lists.newArrayList(); for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) { formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue())); } // encode form parameters and add UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add multipart file upload /////////////////////////////////////////////////////////////////// if (httpRequest.filesToUpload != null) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) { // For File parameters entity.addPart(entry.getKey(), new FileBody((File) entry.getValue())); } apacheHttpRequest.setEntity(entity); } /////////////////////////////////////////////////////////////////// // Or add payload and convert if Json or Xml /////////////////////////////////////////////////////////////////// if (httpRequest.payload != null) { if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) { String string = new ObjectMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType("application/json; charset=utf-8"); apacheHttpRequest.setEntity(entity); } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE) && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) { String string = new XmlMapper().writeValueAsString(httpRequest.payload); StringEntity entity = new StringEntity(string, "utf-8"); entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8); apacheHttpRequest.setEntity(new StringEntity(string, "utf-8")); } else if (httpRequest.payload instanceof String) { StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8"); apacheHttpRequest.setEntity(entity); } else { StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8"); apacheHttpRequest.setEntity(entity); } } setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects); // Here we go! apacheHttpClientResponse = httpClient.execute(apacheHttpRequest); response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse); apacheHttpRequest.releaseConnection(); } catch (IOException e) { logger.error("Fatal problem creating POST or PUT request in TestBrowser", e); throw new RuntimeException(e); } return response; }
From source file:org.megam.deccanplato.provider.box.handler.FileImpl.java
/** * @return/*w ww . j av a 2 s. c o m*/ */ private Map<String, String> upload() { Map<String, String> outMap = new HashMap<>(); final String BOX_UPLOAD = "/files/content"; Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN)); MultipartEntity entity = new MultipartEntity(); FileBody filename = new FileBody(new File(args.get(FILE_NAME))); FileBody filename1 = new FileBody(new File("/home/pandiyaraja/Documents/AMIs")); StringBody parent_id = null; try { parent_id = new StringBody(args.get(FOLDER_ID)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.addPart("filename", filename); entity.addPart("parent_id", parent_id); TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap); tools.setFileEntity(entity); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { ce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } outMap.put(OUTPUT, responseBody); return outMap; }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java
/** * Sends data to create and train a classifier, and returns information about the new * classifier. The status has the value of `Training` when the operation is * successful, and might remain at this status for a while. * * @param name the classifier name * @param language IETF primary language for the classifier * @param csvTrainingData the CSV training data * @return the classifier/* w ww. j a v a 2 s .c om*/ * @see Classifier */ public Classifier createClassifier(final String name, final String language, final File csvTrainingData) { if (csvTrainingData == null || !csvTrainingData.exists()) throw new IllegalArgumentException("csvTrainingData can not be null or not be found"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("language", language == null ? LANGUAGE_EN : language); if (name != null && !name.isEmpty()) { contentJson.addProperty("name", name); } try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("training_data", new FileBody(csvTrainingData)); reqEntity.addPart("training_metadata", new StringBody(contentJson.toString())); HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build(); HttpHost proxy = new HttpHost("10.100.1.124", 3128); ConnRouteParams.setDefaultProxy(request.getParams(), proxy); HttpResponse response = execute(request); return ResponseUtil.getObject(response, Classifier.class); } catch (IOException e) { throw new RuntimeException(e); } }