List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity(final HttpMultipartMode mode)
From source file:net.kidlogger.kidlogger.SendTestReport.java
private void sendPOST() { File fs = getFile();//from w w w . j av a 2s . c o m Date now = new Date(); String fileDate = String.format("%td/%tm/%tY %tT", now, now, now, now); String devField = Settings.getDeviceField(context); if (devField.equals("undefined") || devField.equals("")) return; try { HttpClient client = new DefaultHttpClient(); String postUrl = context.getString(R.string.upload_link); //String postUrl = "http://10.0.2.2/denwer/"; HttpPost post = new HttpPost(postUrl); FileBody bin = new FileBody(fs, "text/html", fs.getName()); StringBody sb1 = new StringBody(devField); StringBody sb2 = new StringBody("HTML"); StringBody sb3 = new StringBody("Andriod_2_2"); StringBody sb4 = new StringBody("1.0"); StringBody sb5 = new StringBody(fileDate); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT); reqEntity.addPart("file", bin); reqEntity.addPart("device", sb1); reqEntity.addPart("content", sb2); reqEntity.addPart("client-ver", sb3); reqEntity.addPart("app-ver", sb4); reqEntity.addPart("client-date-time", sb5); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String pStatus = EntityUtils.toString(resEntity); if (pStatus.equalsIgnoreCase("Ok")) { fs.delete(); testRes.setText("Response: " + pStatus); } else { //Log.i("sendPOST", pStatus); } testRes.setText("Response: " + pStatus); //Log.i("sendPOST", "Response: " + pStatus); } } catch (Exception e) { //Log.i("sendPOST", e.toString()); } }
From source file:com.mobisys.android.ibp.ObservationRequestQueue.java
private void uploadImage(final boolean single, final Bundle b, final Context context, final ArrayList<String> imageStringPath, ArrayList<String> imageType, final ObservationInstance sp) { MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (b != null) Log.d("ObservationRequestQueue", "Params: " + b.toString()); int countUri = 0; for (int i = 0; i < imageStringPath.size(); i++) { if (!imageStringPath.get(i).contains("http://")) { FileBody bab;/*from w w w . j a v a2 s. c o m*/ if (imageType.get(i) != null) bab = new FileBody(new File(imageStringPath.get(i)), imageType.get(i)); // image path and image type else bab = new FileBody(new File(imageStringPath.get(i)), "image/jpeg"); // image p reqEntity.addPart("resources", bab); ++countUri; } } // if imagestring path has no Image url's. if (countUri != 0) { try { reqEntity.addPart(Request.RESOURCE_TYPE, new StringBody("species.participation.Observation")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } WebService.sendMultiPartRequest(context, Request.METHOD_POST, Request.PATH_UPLOAD_RESOURCE, new ResponseHandler() { @Override public void onSuccess(String response) { sp.setStatus(StatusType.PROCESSING); ObservationInstanceTable.updateRowFromTable(context, sp); parseUploadResourceDetail(response, single, b, context, sp, imageStringPath); } @Override public void onFailure(Throwable e, String content) { Log.d("NetWorkState", content); if (e instanceof UnknownHostException || e instanceof ConnectException) { mIsRunning = false; return; } sp.setStatus(StatusType.FAILURE); sp.setMessage(content); ObservationInstanceTable.updateRowFromTable(context, sp); //ObservationParamsTable.deleteRowFromTable(context, sp); if (!single) { ObservationInstance sp_new = ObservationInstanceTable.getFirstRecord(context); observationMethods(single, sp_new, context); } } }, reqEntity); } else { // if all are url's for (int i = 0; i < imageStringPath.size(); i++) { b.putString("file_" + (i + 1), imageStringPath.get(i) .replace("http://" + HttpUtils.stageOrProdBaseURL() + "/biodiv/observations/", "")); b.putString("type_" + (i + 1), Constants.IMAGE); b.putString("license_" + (i + 1), "CC_BY"); } submitObservationRequestFinally(single, b, context, sp); } }
From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java
private static MultipartEntity getMultipartEntity(HttpServletRequest request) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); Enumeration<String> en = request.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String value = request.getParameter(name); try {/* w ww .j a va 2s . c om*/ if (name.equals("file")) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(10000000);// 10 Mo List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); File file = new File(item.getName()); FileOutputStream fos = new FileOutputStream(file); fos.write(item.get()); fos.flush(); fos.close(); entity.addPart(name, new FileBody(file, "application/zip")); } } else { entity.addPart(name, new StringBody(value.toString(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileUploadException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (FileNotFoundException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return entity; }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequestWithAddedServlet() throws IOException { TestHttpClient client = new TestHttpClient(); try {/*from w w w . j ava2 s . c o m*/ String uri = DefaultServer.getDefaultServerURL() + "/servletContext/added"; 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(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(); } }
From source file:ua.pp.msk.gradle.http.Client.java
public boolean upload(NexusConf nc) throws ArtifactPromotionException { boolean result = false; String possibleFailReason = "Unknown"; try {/*from w ww .ja va 2 s.c o m*/ HttpPost httpPost = new HttpPost(targetUrl.toString()); MultipartEntity me = new MultipartEntity(HttpMultipartMode.STRICT); // FormBodyPart fbp = new FormBodyPart("form", new StringBody("check it")); // fbp.addField("r", nc.getRepository()); // fbp.addField("hasPom", "" + nc.isHasPom()); // fbp.addField("e", nc.getExtension()); // fbp.addField("g", nc.getGroup()); // fbp.addField("a", nc.getArtifact()); // fbp.addField("v", nc.getVersion()); // fbp.addField("p", nc.getPackaging()); // me.addPart(fbp); File rpmFile = new File(nc.getFile()); ContentBody cb = new FileBody(rpmFile); me.addPart("p", new StringBody(nc.getPackaging())); me.addPart("e", new StringBody(nc.getExtension())); me.addPart("r", new StringBody(nc.getRepository())); me.addPart("g", new StringBody(nc.getGroup())); me.addPart("a", new StringBody(nc.getArtifact())); me.addPart("v", new StringBody(nc.getVersion())); me.addPart("c", new StringBody(nc.getClassifier())); me.addPart("file", cb); httpPost.setHeader("User-Agent", userAgent); httpPost.setEntity(me); logger.debug("Sending request"); HttpResponse postResponse = client.execute(httpPost, context); logger.debug("Status line: " + postResponse.getStatusLine().toString()); int statusCode = postResponse.getStatusLine().getStatusCode(); HttpEntity entity = postResponse.getEntity(); try (BufferedReader bufReader = new BufferedReader(new InputStreamReader(entity.getContent()))) { StringBuilder fsb = new StringBuilder(); bufReader.lines().forEach(e -> { logger.debug(e); fsb.append(e); fsb.append("\n"); }); possibleFailReason = fsb.toString(); } catch (IOException ex) { logger.warn("Cannot get entity response", ex); } switch (statusCode) { case 200: logger.debug("Got a successful http response " + postResponse.getStatusLine()); result = true; break; case 201: logger.debug("Created! Got a successful http response " + postResponse.getStatusLine()); result = true; break; case 401: throw new BadCredentialsException( "Bad credentials. Response status: " + postResponse.getStatusLine()); default: throw new ResponseException( String.format("Response is not OK. Response status: %s\n\tPossible reason: %s", postResponse.getStatusLine(), possibleFailReason)); } EntityUtils.consume(entity); } catch (UnsupportedEncodingException ex) { logger.error("Encoding is unsuported ", ex); throw new ArtifactPromotionException("Encoding is unsuported " + ex.getMessage()); } catch (IOException ex) { logger.error("Got IO excepption ", ex); throw new ArtifactPromotionException("Input/Output error " + ex.getMessage()); } catch (ResponseException | BadCredentialsException ex) { logger.error("Cannot upload artifact", ex); throw new ArtifactPromotionException("Cannot upload artifact " + ex.getMessage()); } return result; }
From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java
@Test public void testFileUploadWithEagerParsing() throws Exception { DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler())); TestHttpClient client = new TestHttpClient(); try {// w ww. j a v a 2s . c o m 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(); } }
From source file:ecblast.test.EcblastTest.java
public String atomAtomMappingSMI(String query, String type) throws FileNotFoundException, UnsupportedEncodingException, IOException { ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(MultiPartWriter.class); Client client = Client.create(cc);//from w w w . j a v a2 s . co m String urlString = "http://localhost:8080/ecblast-rest/aam"; WebResource webResource = client.resource("http://localhost:8080/ecblast-rest/aam"); //String smi = "[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12])[CH3:6].[H:30][OH:14]>>[H:30][O:4][C:2](=[O:3])[CH2:1][CH:11]([OH:13])[CH3:12].[O:9]=[C:8]([OH:10])[CH2:7][CH:5]([OH:14])[CH3:6]"; FormDataMultiPart form = new FormDataMultiPart(); switch (type) { case "SMI": form.field("q", query); form.field("Q", "SMI"); break; case "RXN": /*MultivaluedMapImpl values = new MultivaluedMapImpl(); values.add("q", new File(query)); values.add("Q", "RXN"); ClientResponse response = webResource.type(MediaType.).post(ClientResponse.class, values); return response.toString(); File attachment = new File(query); FileInputStream fis = null; fis = new FileInputStream(attachment); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { bos.write(buf, 0, readNum); //no doubt here is 0 } fis.close(); bos.close(); } catch (IOException ex) { try { fis.close(); bos.close(); } catch (IOException e) { return "ERROR"; } return "ERROR"; } byte[] bytes = bos.toByteArray(); FormDataBodyPart bodyPart = new FormDataBodyPart("q", new ByteArrayInputStream(bytes), MediaType.APPLICATION_OCTET_STREAM_TYPE); form.bodyPart(bodyPart); //form.field("q", bodyPart); //form.field* form.field("Q", "RXN", MediaType.MULTIPART_FORM_DATA_TYPE);*/ DefaultHttpClient client1; client1 = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(urlString); MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // FileBody queryFileBody = new FileBody(queryFile); multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); File file = new File(query); FileBody fileBody = new FileBody(file); //Prepare payload multiPartEntity.addPart("q", fileBody); multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); //Set to request body postRequest.setEntity(multiPartEntity); //Send request HttpResponse response = client1.execute(postRequest); return response.toString(); } form.setMediaType(MediaType.MULTIPART_FORM_DATA_TYPE); ClientResponse responseJson = webResource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); return responseJson.toString(); }
From source file:net.yama.android.managers.connection.OAuthConnectionManager.java
/** * Special request for photo upload since OAuth doesn't handle multipart/form-data *//* w w w . j av a 2 s . c om*/ public String uploadPhoto(WritePhotoRequest request) throws ApplicationException { String responseString = null; try { OAuthAccessor accessor = new OAuthAccessor(OAuthConnectionManager.consumer); accessor.accessToken = ConfigurationManager.instance.getAccessToken(); accessor.tokenSecret = ConfigurationManager.instance.getAccessTokenSecret(); String tempImagePath = request.getParameterMap().remove(Constants.TEMP_IMAGE_FILE_PATH); String eventId = request.getParameterMap().remove(Constants.EVENT_ID_KEY); ArrayList<Map.Entry<String, String>> params = new ArrayList<Map.Entry<String, String>>(); convertRequestParamsToOAuth(params, request.getParameterMap()); OAuthMessage message = new OAuthMessage(request.getMethod(), request.getRequestURL(), params); message.addRequiredParameters(accessor); List<Map.Entry<String, String>> oAuthParams = message.getParameters(); String url = OAuth.addParameters(request.getRequestURL(), oAuthParams); HttpPost post = new HttpPost(url); File photoFile = new File(tempImagePath); FileBody photoContentBody = new FileBody(photoFile); StringBody eventIdBody = new StringBody(eventId); HttpClient client = new DefaultHttpClient(); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT); reqEntity.addPart(Constants.PHOTO, photoContentBody); reqEntity.addPart(Constants.EVENT_ID_KEY, eventIdBody); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); responseString = EntityUtils.toString(resEntity); } catch (Exception e) { Log.e("OAuthConnectionManager", "Exception in uploadPhoto()", e); throw new ApplicationException(e); } return responseString; }
From source file:ninja.utils.NinjaTestBrowser.java
public String uploadFile(String url, String paramName, File fileToUpload) { String response = null;// w w w .j av a 2 s . co m try { httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // For File parameters entity.addPart(paramName, new FileBody((File) fileToUpload)); post.setEntity(entity); // Here we go! response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8"); post.releaseConnection(); } catch (Exception e) { throw new RuntimeException(e); } return response; }
From source file:org.apache.hadoop.hdfs.qjournal.server.TestJournalNodeImageUpload.java
static HttpPost createRequest(String httpAddress, ContentBody cb) { HttpPost postRequest = new HttpPost(httpAddress + "/uploadImage"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("file", cb); postRequest.setEntity(reqEntity);// ww w .ja v a2s.c om return postRequest; }