List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE
HttpMultipartMode BROWSER_COMPATIBLE
To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.
Click Source Link
From source file:fedroot.dacs.http.DacsPostRequest.java
/** * the following, which includes parameters in the multipart entity is not grokked * by DACS multipart parsing/*from www. ja v a 2s . c om*/ * @param webServiceRequest * @return */ private HttpPost multipartBrokenPost(WebServiceRequest webServiceRequest) { try { HttpPost multipartPost = new HttpPost(webServiceRequest.getBaseURI()); // multipartPost.setHeader("Content-Type", webServiceRequest.getEnclosureType()); multipartPost.setHeader("Content-Transfer-Encoding", "7bit"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "----HttpClientBoundarynSbUMwsZpJVNlFYK", Charset.forName("US-ASCII")); for (NameValuePair nameValuePair : webServiceRequest.getNameValuePairs()) { multipartEntity.addPart(nameValuePair.getName(), new StringBody(new String(nameValuePair.getValue().getBytes(), Charset.forName("US-ASCII")), Charset.forName("US-ASCII"))); } for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) { multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody()); } multipartPost.setEntity(multipartEntity); return multipartPost; } catch (UnsupportedEncodingException ex) { Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage()); } }
From source file:net.ladenthin.snowman.imager.run.uploader.Uploader.java
@Override public void run() { final CImager cs = ConfigurationSingleton.ConfigurationSingleton.getImager(); final String url = cs.getSnowmanServer().getApiUrl(); for (;;) {//from ww w . j a va2 s .c o m File obtainedFile; for (;;) { if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) { LOGGER.trace("killFlag == true"); return; } obtainedFile = FileAssignationSingleton.FileAssignationSingleton.obtainFile(); if (obtainedFile == null) { Imager.waitALittleBit(300); continue; } else { break; } } boolean doUpload = true; while (doUpload) { try { try (CloseableHttpClient httpclient = HttpClients.createDefault()) { final HttpPost httppost = new HttpPost(url); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); final FileBody fb = new FileBody(obtainedFile, ContentType.APPLICATION_OCTET_STREAM); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart(uploadNameCameraimage, fb); builder.addTextBody(uploadNameFilename, obtainedFile.getName()); builder.addTextBody(uploadNameUsername, cs.getSnowmanServer().getUsername()); builder.addTextBody(uploadNamePassword, cs.getSnowmanServer().getPassword()); builder.addTextBody(uploadNameCameraname, cs.getSnowmanServer().getCameraname()); final HttpEntity httpEntity = builder.build(); httppost.setEntity(httpEntity); if (LOGGER.isTraceEnabled()) { LOGGER.trace("executing request " + httppost.getRequestLine()); } try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("response.getStatusLine(): " + response.getStatusLine()); } final HttpEntity resEntity = response.getEntity(); if (resEntity != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("RresEntity.getContentLength(): " + resEntity.getContentLength()); } } final String resString = EntityUtils.toString(resEntity).trim(); EntityUtils.consume(resEntity); if (resString.equals(responseSuccess)) { doUpload = false; LOGGER.trace("true: resString.equals(responseSuccess)"); LOGGER.trace("resString: {}", resString); } else { LOGGER.warn("false: resString.equals(responseSuccess)"); LOGGER.warn("resString: {}", resString); // do not flood log files if an error occurred Imager.waitALittleBit(2000); } } } } catch (NoHttpResponseException | SocketException e) { logIOExceptionAndWait(e); } catch (IOException e) { LOGGER.warn("Found unknown IOException", e); } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete obtainedFile {}", obtainedFile); } final boolean delete = obtainedFile.delete(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("delete success {}", delete); } FileAssignationSingleton.FileAssignationSingleton.freeFile(obtainedFile); } }
From source file:org.craftercms.social.util.UGCHttpClient.java
private HttpPost manageAttachments(String[] attachments, String ticket, String target, String textContent) throws UnsupportedEncodingException, URISyntaxException { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("ticket", ticket)); URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/" + "create.json", URLEncodedUtils.format(qparams, HTTP.UTF_8), null); HttpPost httppost = new HttpPost(uri); if (attachments.length > 0) { MultipartEntity me = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file;/* w w w . j a v a 2 s. com*/ FileBody fileBody; for (String f : attachments) { file = new File(f); fileBody = new FileBody(file, "application/octect-stream"); me.addPart("attachments", fileBody); } //File file = new File(attachments[0]); //FileBody fileBody = new FileBody(file, "application/octect-stream") ; //me.addPart("attachments", fileBody) ; me.addPart("target", new StringBody(target)); me.addPart("textContent", new StringBody(textContent)); httppost.setEntity(me); } return httppost; }
From source file:me.ziccard.secureit.async.AudioRecorderTask.java
@Override public void run() { MicrophoneTaskFactory.pauseSampling(); while (MicrophoneTaskFactory.isSampling()) { try {//from w w w .j ava 2 s . c o m Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } recording = true; final MediaRecorder recorder = new MediaRecorder(); ContentValues values = new ContentValues(3); values.put(MediaStore.MediaColumns.TITLE, filename); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); String audioPath = Environment.getExternalStorageDirectory().getPath() + filename + ".m4a"; recorder.setOutputFile(audioPath); try { recorder.prepare(); } catch (Exception e) { e.printStackTrace(); return; } Log.i("AudioRecorderTask", "Start recording"); recorder.start(); try { Thread.sleep(prefs.getAudioLenght()); } catch (InterruptedException e) { e.printStackTrace(); } recorder.stop(); Log.i("AudioRecorderTask", "Stopped recording"); recorder.release(); recording = false; MicrophoneTaskFactory.restartSampling(); /* * Uploading the audio */ Log.i("AudioRecorderTask", "Trying to upload"); HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); Log.i("AudioRecorderTask", "URI: " + Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_AUDIO); /* * Getting the audio from the file system */ MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File audio = new File(audioPath); reqEntity.addPart("audio", new FileBody(audio, "audio/mp3")); request.setEntity(reqEntity); /* * Authentication token */ request.setHeader("access_token", accessToken); try { HttpResponse response = httpclient.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); StringBuilder builder = new StringBuilder(); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } Log.i("AudioRecorderTask", "Response:\n" + builder.toString()); if (response.getStatusLine().getStatusCode() != 200) { Log.i("AudioRecorderTask", "Error uploading audio: " + audioPath); throw new HttpException(); } } catch (Exception e) { Log.e("DataUploaderTask", "Error uploading audio: " + audioPath); } }
From source file:com.tremolosecurity.proxy.postProcess.PushRequestProcess.java
@Override public void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpFilterChain chain) throws Exception { boolean isText; HashMap<String, String> uriParams = (HashMap<String, String>) req.getAttribute("TREMOLO_URI_PARAMS"); StringBuffer proxyToURL = new StringBuffer(); proxyToURL.append(holder.getProxyURL(uriParams)); boolean first = true; for (NVP p : req.getQueryStringParams()) { if (first) { proxyToURL.append('?'); first = false;//from w w w . j a v a2 s . c o m } else { proxyToURL.append('&'); } proxyToURL.append(p.getName()).append('=').append(URLEncoder.encode(p.getValue(), "UTF-8")); } HttpEntity entity = null; if (req.isMultiPart()) { MultipartEntityBuilder mpeb = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE); for (String name : req.getFormParams()) { /*if (queryParams.contains(name)) { continue; }*/ for (String val : req.getFormParamVals(name)) { //ent.addPart(name, new StringBody(val)); mpeb.addTextBody(name, val); } } HashMap<String, ArrayList<FileItem>> files = req.getFiles(); for (String name : files.keySet()) { for (FileItem fi : files.get(name)) { //ent.addPart(name, new InputStreamBody(fi.getInputStream(),fi.getContentType(),fi.getName())); mpeb.addBinaryBody(name, fi.get(), ContentType.create(fi.getContentType()), fi.getName()); } } entity = mpeb.build(); } else if (req.isParamsInBody()) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (String paramName : req.getFormParams()) { for (String val : req.getFormParamVals(paramName)) { formparams.add(new BasicNameValuePair(paramName, val)); } } entity = new UrlEncodedFormEntity(formparams, "UTF-8"); } else { byte[] msgData = (byte[]) req.getAttribute(ProxySys.MSG_BODY); ByteArrayEntity bentity = new ByteArrayEntity(msgData); bentity.setContentType(req.getContentType()); entity = bentity; } MultipartRequestEntity frm; CloseableHttpClient httpclient = this.getHttp(proxyToURL.toString(), req.getServletRequest(), holder.getConfig()); //HttpPost httppost = new HttpPost(proxyToURL.toString()); HttpEntityEnclosingRequestBase httpMethod = new EntityMethod(req.getMethod(), proxyToURL.toString());//this.getHttpMethod(proxyToURL.toString()); setHeadersCookies(req, holder, httpMethod, proxyToURL.toString()); httpMethod.setEntity(entity); HttpContext ctx = (HttpContext) req.getSession().getAttribute(ProxySys.HTTP_CTX); HttpResponse response = httpclient.execute(httpMethod, ctx); postProcess(req, resp, holder, response, proxyToURL.toString(), chain, httpMethod); }
From source file:gov.nasa.arc.geocam.talk.service.SiteAuthCookie.java
@Override public ServerResponse post(String relativePath, Map<String, String> params, byte[] audioBytes) throws AuthenticationFailedException, IOException, ClientProtocolException, InvalidParameterException { if (params == null) { throw new InvalidParameterException("Post parameters are required"); }//from ww w . jav a2 s . c o m ensureAuthenticated(); httpClient = new DefaultHttpClient(); HttpParams httpParams = httpClient.getParams(); HttpClientParams.setRedirecting(httpParams, false); HttpPost post = new HttpPost(this.serverRootUrl + "/" + appPath + "/" + relativePath); post.setParams(httpParams); HttpEntity httpEntity; if (audioBytes != null) { httpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (String key : params.keySet()) { ((MultipartEntity) httpEntity).addPart(key, new StringBody(params.get(key))); } if (audioBytes != null) { ((MultipartEntity) httpEntity).addPart("audio", new ByteArrayBody(audioBytes, "audio/mpeg", "audio.mp4")); } } else { List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(); for (String key : params.keySet()) { nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); } httpEntity = new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII); } post.setEntity(httpEntity); httpClient.getCookieStore().addCookie(sessionIdCookie); ServerResponse sr = new ServerResponse(httpClient.execute(post)); if (sr.getResponseCode() == 401 || sr.getResponseCode() == 403) { throw new AuthenticationFailedException("Server responded with code: " + sr.getResponseCode()); } return sr; }
From source file:org.fabrician.maven.plugins.GridlibUploadMojo.java
public void execute() throws MojoExecutionException { String username = brokerUsername; String password = brokerPassword; if (serverId != null && !"".equals(serverId)) { // TODO: implement server_id throw new MojoExecutionException("serverId is not yet supported"); } else if (brokerUsername == null || "".equals(brokerUsername) || brokerPassword == null || "".equals(brokerPassword)) { throw new MojoExecutionException("serverId or brokerUsername and brokerPassword must be set"); }//from w w w. ja v a 2 s. c om DirectoryScanner ds = new DirectoryScanner(); ds.setIncludes(mIncludes); ds.setExcludes(mExcludes); ds.setBasedir("."); ds.setCaseSensitive(true); ds.scan(); String[] files = ds.getIncludedFiles(); if (files == null) { getLog().info("No files found to upload"); } else { getLog().info("Found " + files.length + " file to upload"); for (String file : files) { File gridlibFilename = new File(file); getLog().info("Uploading " + gridlibFilename + " to " + brokerUrl); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); Credentials cred = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, cred); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("gridlibOverwrite", new StringBody(String.valueOf(gridlibOverwrite), Charset.forName("UTF-8"))); entity.addPart("gridlibArchive", new FileBody(gridlibFilename)); HttpPost method = new HttpPost(brokerUrl); method.setEntity(entity); HttpResponse response = httpclient.execute(method); StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code >= 400 && code <= 500) { throw new MojoExecutionException( "Failed to upload " + gridlibFilename + " to " + brokerUrl + ": " + code); } } catch (Exception e) { throw new MojoExecutionException(e.getMessage()); } } } }
From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java
@Override protected void onHandleIntent(Intent intent) { // initialize // extract details Server server = intent.getParcelableExtra("server"); String directory = intent.getStringExtra("directory"); String filename = intent.getStringExtra("filename"); // get the json parser from the application JsonParser jsonParser = new JsonParser(); // start the ball rolling... final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); final NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setTicker(String.format(getString(R.string.notif_ticker), filename)) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large)) .setSmallIcon(R.drawable.ic_stat_notif_small) .setContentTitle(String.format(getString(R.string.notif_title), filename)) .setContentText(getString(R.string.notif_content_init)) // to avoid NPE on android 2.x where content intent is required // set an empty content intent .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true); // notify user that upload is starting mgr.notify(NOTIFICATION_ID, builder.build()); // reset ticker for any subsequent notifications builder.setTicker(null);//from w w w .j a v a 2s. co m AbstractHttpClient client = CustomHTTPClient.getHttpClient(); // enable digest authentication if (server.getUsername() != null && !server.getUsername().equals("")) { Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword()); client.getCredentialsProvider().setCredentials( new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials); } final File file = new File(directory, filename); final long length = file.length(); try { CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { @Override public void transferred(long num) { // calculate percentage //System.out.println("transferred: " + num); int progress = (int) ((num * 100) / length); builder.setContentText(String.format(getString(R.string.notif_content), progress)); mgr.notify(NOTIFICATION_ID, builder.build()); } }); multipart.addPart(file.getName(), new FileBody(file)); HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content"); httpRequest.setEntity(multipart); HttpResponse serverResponse = client.execute(httpRequest); BasicResponseHandler handler = new BasicResponseHandler(); JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject(); if (!reply.has("outcome")) { throw new RuntimeException(getString(R.string.invalid_response)); } else { // remove the 'upload in-progress' notification mgr.cancel(NOTIFICATION_ID); String outcome = reply.get("outcome").getAsString(); if (outcome.equals("success")) { String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString(); Intent resultIntent = new Intent(this, UploadCompletedActivity.class); // populate it resultIntent.putExtra("server", server); resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE); resultIntent.putExtra("filename", filename); resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // the notification id for the 'completed upload' notification // each completed upload will have a different id int notifCompletedID = (int) System.currentTimeMillis(); builder.setContentTitle(getString(R.string.notif_title_uploaded)) .setContentText(String.format(getString(R.string.notif_content_uploaded), filename)) .setContentIntent( // we set the (2nd param request code to completedID) // see http://tinyurl.com/kkcedju PendingIntent.getActivity(this, notifCompletedID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)) .setAutoCancel(true).setOngoing(false); mgr.notify(notifCompletedID, builder.build()); } else { JsonElement elem = reply.get("failure-description"); if (elem.isJsonPrimitive()) { throw new RuntimeException(elem.getAsString()); } else if (elem.isJsonObject()) throw new RuntimeException( elem.getAsJsonObject().get("domain-failure-description").getAsString()); } } } catch (Exception e) { builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false); mgr.notify(NOTIFICATION_ID, builder.build()); } }
From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java
private static HttpUriRequest getUploadFileRequest(String method, URI uri, ContentBody contentBody, @Nullable List<Header> headers, @Nullable List<NameValuePair> parameters, int socketTimeoutMs) { // Build the Http entity HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart(contentBody.getFilename(), contentBody).build(); // Build the request RequestBuilder requestBuilder = RequestBuilder.create(method).setVersion(HttpVersion.HTTP_1_1).setUri(uri) .setEntity(entity);/*from w w w.ja v a 2 s . c o m*/ addHeadersAndParameters(requestBuilder, headers, parameters); setTimeout(requestBuilder, socketTimeoutMs); return requestBuilder.build(); }
From source file:org.casquesrouges.missing.HttpAdapter.java
@Override public void run() { handler.sendMessage(Message.obtain(handler, HttpAdapter.START)); httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, 80), new UsernamePasswordCredentials(login, pass)); HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000); try {//from ww w . ja v a 2 s . c o m HttpResponse response = null; switch (method) { case GET: response = httpClient.execute(new HttpGet(url)); break; case POST: HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(data)); response = httpClient.execute(httpPost); break; case FILE: File input = new File(picFile); HttpPost post = new HttpPost(url); MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multi.addPart("person_id", new StringBody(Integer.toString(personID))); multi.addPart("creator_id", new StringBody(creator_id)); multi.addPart("file", new FileBody(input)); post.setEntity(multi); Log.d("MISSING", "http FILE: " + url + " pic: " + picFile); response = httpClient.execute(post); break; } processEntity(response); } catch (Exception e) { handler.sendMessage(Message.obtain(handler, HttpAdapter.ERROR, e)); } ConnectionManager.getInstance().didComplete(this); }