List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:niclients.main.pubni.java
/** * Creates NI publish HTTP POST signal./*from w w w . j av a2 s . c o m*/ * * @return boolean true/false in success/failure * @throws UnsupportedEncodingException */ static boolean createpub() throws UnsupportedEncodingException { post = new HttpPost(fqdn + "/.well-known/netinfproto/publish"); ContentBody url = new StringBody(niname); ContentBody msgid = new StringBody(Integer.toString(randomGenerator.nextInt(100000000))); ContentBody fullPut = new StringBody("yes"); ContentBody ext = new StringBody("no extension"); ContentBody bin = new FileBody(new File(filename)); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("octets", bin); reqEntity.addPart("URI", url); reqEntity.addPart("msgid", msgid); reqEntity.addPart("fullPut", fullPut); reqEntity.addPart("ext", ext); post.setEntity(reqEntity); return true; }
From source file:jp.tonyu.soytext2.file.Comm.java
public Scriptable execMultiPart(String rootPath, String relPath, final Scriptable sparams, Object responseType) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(rootPath + relPath); final MultipartEntity reqEntity = new MultipartEntity(); Scriptables.each(sparams, new StringPropAction() { @Override/* w w w . jav a 2 s.com*/ public void run(String key, Object value) { if (value instanceof String) { String s = (String) value; try { reqEntity.addPart(key, new StringBody(s, Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else if (value instanceof Scriptable) { Scriptable s = (Scriptable) value; String filename = (String) ScriptableObject.getProperty(s, FileUpload.FILENAME); Object body = ScriptableObject.getProperty(s, FileUpload.BODY); InputStream st = null; if (body instanceof InputStream) { st = (InputStream) body; } else if (body instanceof ReadableBinData) { ReadableBinData rbd = (ReadableBinData) body; try { st = rbd.getInputStream(); } catch (IOException e) { Log.die(e); } } if (st == null) throw new RuntimeException("Not a bindata - " + body); InputStreamBody bin = new InputStreamBody(st, filename); reqEntity.addPart(key, bin); } } }); httppost.setEntity(reqEntity); Log.d(this, "executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); Scriptable res = response2Scriptable(response, responseType); return res; }
From source file:com.globalsight.everest.tda.TdaHelper.java
public String loginCheck(String hostName, String userName, String password) { int timeoutConnection = 8000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); String errorInfo = new String(); hostName = hostName.trim();//from w w w. ja v a 2 s . c o m userName = userName.trim(); if (hostName.indexOf("http://") < 0) { loginUrl = "http://" + hostName; } else { loginUrl = hostName; } if (hostName.lastIndexOf("/") == (hostName.length() - 1)) { loginUrl = loginUrl + "auth_key.json?action=login"; } else { loginUrl = loginUrl + "/auth_key.json?action=login"; } try { HttpPost httpost = new HttpPost(loginUrl); MultipartEntity reqEntity = new MultipartEntity(); StringBody nameBody = new StringBody(userName); StringBody passwordBody = new StringBody(password); StringBody appKeyBody = new StringBody(appKey); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() == 404) { errorInfo = "The TDA URL is not correct."; } else if (sl.getStatusCode() == 401) { errorInfo = "The username and password given are not a valid TDA login."; } else if (sl.getStatusCode() == 201) { errorInfo = "ture"; } else { errorInfo = "The TDA configuration is not correct!"; } } catch (Exception e) { s_logger.info("Can not connect TDA server:" + e.getMessage()); errorInfo = "Can not connect TDA server."; } return errorInfo; }
From source file:com.woonoz.proxy.servlet.HttpPostRequestHandler.java
private HttpEntity createMultipartEntity(HttpServletRequest request, HttpPost httpPost) throws FileUploadException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartEntity multipartEntity = new MultipartEntity(); FileItemIterator iterator = servletFileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream fileItem = iterator.next(); final String partName = fileItem.getFieldName(); if (fileItem.isFormField()) { multipartEntity.addPart(partName, buildStringBody(fileItem)); } else {/*from ww w. ja va 2 s . c o m*/ multipartEntity.addPart(partName, buildContentBodyFromFileItem(fileItem)); } } return multipartEntity; }
From source file:org.apache.sling.testing.tools.sling.SlingClient.java
/** Create a node at specified path, with optional properties * @param path Used in POST request to Sling server * @param properties If not null, properties are added to the created node * @return The actual path of the node that was created *///w w w . jav a 2 s .c o m public String createNode(String path, Map<String, Object> properties) throws UnsupportedEncodingException, IOException { String actualPath = null; final MultipartEntity entity = new MultipartEntity(); // Add Sling POST options entity.addPart(":redirect", new StringBody("*")); entity.addPart(":displayExtension", new StringBody("")); // Add user properties if (properties != null) { for (Map.Entry<String, Object> e : properties.entrySet()) { entity.addPart(e.getKey(), new StringBody(e.getValue().toString())); } } final HttpResponse response = executor .execute(builder.buildPostRequest(path).withEntity(entity).withCredentials(username, password)) .assertStatus(302).getResponse(); final Header location = response.getFirstHeader(LOCATION_HEADER); assertNotNull("Expecting " + LOCATION_HEADER + " in response", location); actualPath = locationToPath(location.getValue()); return actualPath; }
From source file:com.github.mhendred.face4j.CopyOfResponderImpl.java
/** * @see {@link Responder#doPost(File, URI, List)} *//*from w ww. ja va 2 s.com*/ public String doPost(final File file, final URI uri, final List<NameValuePair> params) throws FaceClientException, FaceServerException { try { final MultipartEntity entity = new MultipartEntity(); entity.addPart("image", new FileBody(file)); try { for (NameValuePair nvp : params) { entity.addPart(nvp.getName(), new StringBody(nvp.getValue())); } } catch (UnsupportedEncodingException uee) { throw new FaceClientException(uee); } postMethod.setURI(uri); postMethod.setEntity(entity); final long start = System.currentTimeMillis(); final HttpResponse response = httpClient.execute(postMethod); return checkResponse(response); } catch (IOException ioe) { throw new FaceClientException(ioe); } }
From source file:io.undertow.servlet.test.charset.ParameterCharacterEncodingTestCase.java
@Test public void testMultipartCharacterEncoding() throws IOException { TestHttpClient client = new TestHttpClient(); try {//w w w .j a v a2 s . c om String message = "abc?"; String charset = "UTF-8"; HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext"); MultipartEntity multipart = new MultipartEntity(); multipart.addPart("charset", new StringBody(charset, Charset.forName(charset))); multipart.addPart("message", new StringBody(message, Charset.forName(charset))); post.setEntity(multipart); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); String response = HttpClientUtils.readResponse(result); Assert.assertEquals(message, response); } finally { client.getConnectionManager().shutdown(); } }
From source file:com.glodon.paas.document.api.FileRestAPITest.java
@Test public void uploadFolderForMultiPart() throws IOException { File parentFile = getFile(simpleCall(createPost("/file/1?folder")), null); java.io.File file = new ClassPathResource("file/testupload.file").getFile(); String uploadUrl = "/file/" + file.getName() + "?upload&position=0&type=path"; HttpPost post = createPost(uploadUrl); FileBody fileBody = new FileBody(file); StringBody sbId = new StringBody(parentFile.getId()); StringBody sbSize = new StringBody(String.valueOf(file.length())); StringBody sbName = new StringBody("aa/" + file.getName()); StringBody sbPosition = new StringBody("0"); MultipartEntity entity = new MultipartEntity(); entity.addPart("fileId", sbId); entity.addPart("size", sbSize); entity.addPart("fileName", sbName); entity.addPart("position", sbPosition); entity.addPart("file", fileBody); post.setEntity(entity);// w ww .j a v a 2 s . c o m File uploadFile = getFile(simpleCall(post), null); assertEquals(file.getName(), uploadFile.getFullName()); assertFalse(uploadFile.isFolder()); File aaFolder = getFile(simpleCall(createGet("/file/1/aa?meta")), "meta"); assertEquals(aaFolder.getId(), uploadFile.getParentId()); }
From source file:org.n52.oss.ui.controllers.ScriptController.java
@RequestMapping(method = RequestMethod.POST, value = "/upload") public String processForm(@ModelAttribute(value = "uploadForm") uploadForm form, ModelMap map) { String s = form.getFile().getFileItem().getName(); MultipartEntity multipartEntity = new MultipartEntity(); UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();//w ww .ja va2 s. c om String token = userDetails.getPassword(); // upload the file File dest = new File(s); try { System.out.println("Chosen license:" + form.getLicense()); log.info("Chosen license:" + form.getLicense()); form.getFile().transferTo(dest); UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication() .getPrincipal(); multipartEntity.addPart("file", new FileBody(dest)); multipartEntity.addPart("user", new StringBody(details.getUsername())); multipartEntity.addPart("licenseCode", new StringBody(form.getLicense())); multipartEntity.addPart("auth_token", new StringBody(token)); HttpPost post = new HttpPost(OSSConstants.BASE_URL + "/OpenSensorSearch/script/submit"); post.setEntity(multipartEntity); org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpResponse resp; resp = client.execute(post); int responseCode = resp.getStatusLine().getStatusCode(); StringBuilder builder = new StringBuilder(); String str = null; BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); while ((str = reader.readLine()) != null) builder.append(str); System.out.println("return id:" + builder.toString()); log.info("return id:" + builder.toString()); if (responseCode == 200) { map.addAttribute("harvestSuccess", true); map.addAttribute("resultScript", builder.toString()); map.addAttribute("license", form.getLicense()); return "script/status"; } else { map.addAttribute("harvestError", true); return "script/status"; } } catch (Exception e) { map.addAttribute("errorMSG", e); return "script/status?fail"; } }