List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:interactivespaces.util.web.HttpClientHttpContentCopier.java
/** * Perform the actual content copy./*from ww w. jav a 2 s .c o m*/ * * @param destinationUri * URI for the destination * @param sourceParameterName * the parameter name in the HTTP form post for the content * @param params * the parameters to be included, can be {@code null} * @param contentBody * the content to be sent */ private void doCopyTo(String destinationUri, String sourceParameterName, Map<String, String> params, AbstractContentBody contentBody) { HttpEntity entity = null; try { HttpPost httpPost = new HttpPost(destinationUri); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart(sourceParameterName, contentBody); if (params != null) { for (Entry<String, String> entry : params.entrySet()) { mpEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } } httpPost.setEntity(mpEntity); HttpResponse response = httpClient.execute(httpPost); entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new SimpleInteractiveSpacesException( String.format("Server returned bad status code %d for source URI %s during HTTP copy", statusCode, destinationUri)); } } catch (InteractiveSpacesException e) { throw e; } catch (Exception e) { throw new InteractiveSpacesException( String.format("Could not send file to destination URI %s during HTTP copy", destinationUri), e); } finally { if (entity != null) { try { EntityUtils.consume(entity); } catch (IOException e) { throw new InteractiveSpacesException(String .format("Could not consume entity content for %s during HTTP copy", destinationUri), e); } } } }
From source file:com.ushahidi.android.app.net.CommentHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *///w w w .j av a2 s . c om public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException { log("PostFileUpload(): upload file to server."); apiUtils.updateDomain(); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody("comments")); entity.addPart("action", new StringBody("add")); entity.addPart("comment_author", new StringBody(params.get("comment_author"))); entity.addPart("comment_description", new StringBody(params.get("comment_description"), Charset.forName("UTF-8"))); entity.addPart("comment_email", new StringBody(params.get("comment_email"), Charset.forName("UTF-8"))); if ((params.get("incident_id") != null) && (Integer.valueOf(params.get("incident_id")) != 0)) entity.addPart("incident_id", new StringBody(params.get("incident_id"))); if ((params.get("checkin_id") != null) && (Integer.valueOf(params.get("checkin_id")) != 0)) entity.addPart("checkin_id", new StringBody(params.get("checkin_id"), Charset.forName("UTF-8"))); // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); if (serverInput != null) { // TODO:: get the status confirmation code to work //int status = ApiUtils.extractPayloadJSON(GetText(serverInput)); return true; } return false; } } } catch (MalformedURLException ex) { log("PostFileUpload(): MalformedURLException", ex); return false; // fall through and return false } catch (IllegalArgumentException ex) { log("IllegalArgumentException", ex); // invalid URI return false; } catch (IOException e) { log("IOException", e); // timeout return false; } return false; }
From source file:com.surevine.alfresco.connector.BaseAlfrescoHttpConnector.java
/** * POST multipart form parts to a URL using JSON encoding and parse out a JSON * object from the response.//from w w w. j a v a2 s . c o m * * @param url * URL to post to * @param content * The String value of the post request * @return The JSON response * @throws AlfrescoException * On any HTTP error */ protected AlfrescoHttpResponse doHttpPost(final String url, final Map<String, ContentBody> parts) throws AlfrescoException { final HttpPost request = new HttpPost(url); final MultipartEntity entity = new MultipartEntity(); for (final String name : parts.keySet()) { entity.addPart(name, parts.get(name)); } request.setEntity(entity); return fetch(request); }
From source file:functionaltests.RestSchedulerPushPullFileTest.java
public void testIt(String spaceName, String spacePath, String destPath, boolean encode) throws Exception { File testPushFile = RestFuncTHelper.getDefaultJobXmlfile(); // you can test pushing pulling a big file : // testPushFile = new File("path_to_a_big_file"); File destFile = new File(new File(spacePath, destPath), testPushFile.getName()); if (destFile.exists()) { destFile.delete();//from w w w . ja v a 2 s. c o m } // PUSHING THE FILE String pushfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/"))); // either we encode or we test human readable path (with no special character inside) HttpPost reqPush = new HttpPost(pushfileUrl); setSessionHeader(reqPush); // we push a xml job as a simple test MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("fileName", new StringBody(testPushFile.getName())); multipartEntity.addPart("fileContent", new InputStreamBody(FileUtils.openInputStream(testPushFile), MediaType.APPLICATION_OCTET_STREAM, null)); reqPush.setEntity(multipartEntity); HttpResponse response = executeUriRequest(reqPush); System.out.println(response.getStatusLine()); assertHttpStatusOK(response); Assert.assertTrue(destFile + " exists for " + spaceName, destFile.exists()); Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(testPushFile, destFile)); // LISTING THE TARGET DIRECTORY String pullListUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath, "UTF-8") : destPath.replace("\\", "/"))); HttpGet reqPullList = new HttpGet(pullListUrl); setSessionHeader(reqPullList); HttpResponse response2 = executeUriRequest(reqPullList); System.out.println(response2.getStatusLine()); assertHttpStatusOK(response2); InputStream is = response2.getEntity().getContent(); List<String> lines = IOUtils.readLines(is); HashSet<String> content = new HashSet<>(lines); System.out.println(lines); Assert.assertTrue("Pushed file correctly listed", content.contains(testPushFile.getName())); // PULLING THE FILE String pullfileUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(destPath + "/" + testPushFile.getName(), "UTF-8") : destPath.replace("\\", "/") + "/" + testPushFile.getName())); HttpGet reqPull = new HttpGet(pullfileUrl); setSessionHeader(reqPull); HttpResponse response3 = executeUriRequest(reqPull); System.out.println(response3.getStatusLine()); assertHttpStatusOK(response3); InputStream is2 = response3.getEntity().getContent(); File answerFile = tmpFolder.newFile(); FileUtils.copyInputStreamToFile(is2, answerFile); Assert.assertTrue("Original file and result are equals for " + spaceName, FileUtils.contentEquals(answerFile, testPushFile)); // DELETING THE HIERARCHY String rootPath = destPath.substring(0, destPath.contains("/") ? destPath.indexOf("/") : destPath.length()); String deleteUrl = getResourceUrl("dataspace/" + spaceName + "/" + (encode ? URLEncoder.encode(rootPath, "UTF-8") : rootPath.replace("\\", "/"))); HttpDelete reqDelete = new HttpDelete(deleteUrl); setSessionHeader(reqDelete); HttpResponse response4 = executeUriRequest(reqDelete); System.out.println(response4.getStatusLine()); assertHttpStatusOK(response4); Assert.assertTrue(destFile + " still exist", !destFile.exists()); }
From source file:com.fanfou.app.opensource.util.NetworkHelper.java
public static MultipartEntity encodeMultipartParameters(final List<SimpleRequestParam> params) { if (CommonHelper.isEmpty(params)) { return null; }// w w w .ja v a2 s. c om final MultipartEntity entity = new MultipartEntity(); try { for (final SimpleRequestParam param : params) { if (param.isFile()) { entity.addPart(param.getName(), new FileBody(param.getFile())); } else { entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(HTTP.UTF_8))); } } } catch (final UnsupportedEncodingException e) { e.printStackTrace(); } return entity; }
From source file:iqq.im.service.ApacheHttpService.java
@Override public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener) throws QQException { try {/*w w w . j a va 2 s. c o m*/ URI uri = URI.create(request.getUrl()); if (request.getMethod().equals("POST")) { HttpPost httppost = new HttpPost(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout()); } if (request.getFileMap().size() > 0) { MultipartEntity entity = new MultipartEntity(); String charset = request.getCharset(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; entity.addPart(key, new StringBody(value, Charset.forName(charset))); } Map<String, File> fileMap = request.getFileMap(); for (String key : fileMap.keySet()) { File value = fileMap.get(key); entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value)))); } httppost.setEntity(entity); } else if (request.getPostMap().size() > 0) { List<NameValuePair> list = new ArrayList<NameValuePair>(); Map<String, String> postMap = request.getPostMap(); for (String key : postMap.keySet()) { String value = postMap.get(key); value = value == null ? "" : value; list.add(new BasicNameValuePair(key, value)); } httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset())); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httppost.addHeader(key, headerMap.get(key)); } QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener); QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar); QQHttpResponseCallback callback = new QQHttpResponseCallback(listener); Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback); return new ProxyFuture(future, consumer, producer); } else if (request.getMethod().equals("GET")) { HttpGet httpget = new HttpGet(uri); HttpHost httphost = URIUtils.extractHost(uri); if (httphost == null) { LOG.error("host is null, url: " + uri.toString()); httphost = new HttpHost(uri.getHost()); } Map<String, String> headerMap = request.getHeaderMap(); for (String key : headerMap.keySet()) { httpget.addHeader(key, headerMap.get(key)); } if (request.getReadTimeout() > 0) { HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout()); } if (request.getConnectTimeout() > 0) { HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout()); } return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget), new QQHttpResponseConsumer(request, listener, cookieJar), new QQHttpResponseCallback(listener)); } else { throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod()); } } catch (IOException e) { throw new QQException(QQErrorCode.IO_ERROR); } }
From source file:at.ac.tuwien.big.testsuite.impl.validator.WaiValidator.java
@Override public ValidationResult validate(File fileToValidate, String exerciseId) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpPost request = new HttpPost("http://localhost:8080/" + contextPath + "/checker/index.php"); List<ValidationResultEntry> validationResultEntries = new ArrayList<>(); try {/* www. ja v a 2 s . co m*/ MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("uri", new StringBody("")); multipartEntity.addPart("MAX_FILE_SIZE", new StringBody("52428800")); multipartEntity.addPart("uploadfile", new FileBody(fileToValidate, "text/html")); multipartEntity.addPart("validate_file", new StringBody("Check It")); multipartEntity.addPart("pastehtml", new StringBody("")); multipartEntity.addPart("radio_gid[]", new StringBody("8")); multipartEntity.addPart("checkbox_gid[]", new StringBody("8")); multipartEntity.addPart("rpt_format", new StringBody("1")); request.setEntity(multipartEntity); Document doc = httpClient.execute(request, new DomResponseHandler(httpClient, request), httpContext); Element errorsContainer = DomUtils.byId(doc.getDocumentElement(), "AC_errors"); String title = ""; StringBuilder descriptionSb = new StringBuilder(); boolean descriptionStarted = false; for (Element e : DomUtils.asList(errorsContainer.getChildNodes())) { if ("h3".equals(e.getTagName())) { if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } title = e.getTextContent(); descriptionSb.setLength(0); descriptionStarted = false; } else if ("div".equals(e.getTagName()) && e.getAttribute("class").contains("gd_one_check")) { if (descriptionStarted) { descriptionSb.append('\n'); } if (extractDescription(e, descriptionSb)) { descriptionStarted = true; } } } if (descriptionStarted) { validationResultEntries.add(new DefaultValidationResultEntry(title, descriptionSb.toString(), ValidationResultEntryType.ERROR)); } } finally { request.releaseConnection(); } return new DefaultValidationResult("WAI Validation", fileToValidate.getName(), new DefaultValidationResultType("WAI"), validationResultEntries); }
From source file:org.deviceconnect.android.profile.restful.test.NormalFileProfileTestCase.java
/** * ???./* w ww. jav a 2 s .co m*/ * <pre> * Method: POST * Path: /file/send?deviceid=xxxx&filename=xxxx * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testSend() { final String name = "test.png"; URIBuilder builder = TestURIBuilder.createURIBuilder(); builder.setProfile(FileProfileConstants.PROFILE_NAME); builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND); builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()); builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken()); builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/test.png"); builder.addParameter(FileProfileConstants.PARAM_FILE_TYPE, String.valueOf(FileProfileConstants.FileType.FILE.getValue())); AssetManager manager = getApplicationContext().getAssets(); InputStream in = null; try { MultipartEntity entity = new MultipartEntity(); in = manager.open(name); // ?? ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] buf = new byte[BUF_SIZE]; while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } // ? entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name)); HttpPost request = new HttpPost(builder.toString()); request.setEntity(entity); JSONObject root = sendRequest(request); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (IOException e) { fail("IOException in JSONObject." + e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } } }
From source file:org.orbeon.oxf.xforms.submission.XFormsSubmissionUtils.java
/** * Implement support for XForms 1.1 section "11.9.7 Serialization as multipart/form-data". * * @param document XML document to submit * @return MultipartRequestEntity *//*from w ww. j a v a 2 s. c om*/ public static MultipartEntity createMultipartFormData(final Document document) throws IOException { // Visit document final MultipartEntity multipartEntity = new MultipartEntity(); document.accept(new VisitorSupport() { public final void visit(Element element) { try { // Only care about elements // Only consider leaves i.e. elements without children elements final List children = element.elements(); if (children == null || children.size() == 0) { final String value = element.getText(); { // Got one! final String localName = element.getName(); final QName nodeType = InstanceData.getType(element); if (XMLConstants.XS_ANYURI_QNAME.equals(nodeType)) { // Interpret value as xs:anyURI if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:anyURI // Don't close the stream here, as it will get read later when the MultipartEntity // we create here is written to an output stream addPart(multipartEntity, URLFactory.createURL(value).openStream(), element, value); } else { // Value is invalid as per xs:anyURI // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else if (XMLConstants.XS_BASE64BINARY_QNAME.equals(nodeType)) { // Interpret value as xs:base64Binary if (InstanceData.getValid(element) && value.trim().length() > 0) { // Value is valid as per xs:base64Binary addPart(multipartEntity, new ByteArrayInputStream(NetUtils.base64StringToByteArray(value)), element, null); } else { // Value is invalid as per xs:base64Binary // Just use the value as is (could also ignore it) multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } else { // Just use the value as is multipartEntity.addPart(localName, new StringBody(value, Charset.forName("UTF-8"))); } } } } catch (IOException e) { throw new OXFException(e); } } }); return multipartEntity; }
From source file:gov.nist.appvet.tool.synchtest.util.ReportUtil.java
/** This method should be used for sending files back to AppVet. */ public static boolean sendInNewHttpRequest(String appId, String reportFilePath, ToolStatus reportStatus) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 30000); HttpConnectionParams.setSoTimeout(httpParameters, 1200000); HttpClient httpClient = new DefaultHttpClient(httpParameters); httpClient = SSLWrapper.wrapClient(httpClient); try {/* w w w . j a va2 s. com*/ /* * To send reports back to AppVet, the following parameters must be * sent: - command: SUBMIT_REPORT - username: AppVet username - * password: AppVet password - appid: The app ID - toolid: The ID of * this tool - toolrisk: The risk assessment (LOW, MODERATE, HIGH, * ERROR) - report: The report file. */ MultipartEntity entity = new MultipartEntity(); entity.addPart("command", new StringBody("SUBMIT_REPORT", Charset.forName("UTF-8"))); entity.addPart("username", new StringBody(Properties.appvetUsername, Charset.forName("UTF-8"))); entity.addPart("password", new StringBody(Properties.appvetPassword, Charset.forName("UTF-8"))); entity.addPart("appid", new StringBody(appId, Charset.forName("UTF-8"))); entity.addPart("toolid", new StringBody(Properties.toolId, Charset.forName("UTF-8"))); entity.addPart("toolrisk", new StringBody(reportStatus.name(), Charset.forName("UTF-8"))); File report = new File(reportFilePath); FileBody fileBody = new FileBody(report); entity.addPart("file", fileBody); HttpPost httpPost = new HttpPost(Properties.appvetUrl); httpPost.setEntity(entity); // Send the report to AppVet log.debug("Sending report file to AppVet"); final HttpResponse response = httpClient.execute(httpPost); log.debug("Received from AppVet: " + response.getStatusLine()); // Clean up httpPost = null; return true; } catch (Exception e) { log.error(e.toString()); return false; } }