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:com.cottsoft.weedfs.client.WeedfsClient.java
/** * Description<br>// w w w . j av a 2 s . c om * Cache local file to WeedFS Server * * @version v1.0.0 * @param file * @return */ public RequestResult cache(File file) { RequestResult result = null; Gson gson = new Gson(); if (!file.exists()) { throw new IllegalArgumentException("File doesn't exist"); } // HTTP REQUEST begin result = new RequestResult(); WeedAssign assignedInfo = null; BufferedReader in = null; // 1. Send assign request and get fid try { StringBuffer host = new StringBuffer(); host.append("http://"); host.append(this.masterHost); host.append(":"); host.append(this.masterPort); host.append("/"); //HttpUtil.request("http://" + this.masterHost + ":" + this.masterPort+ "/", "dir/assign", "GET") in = new BufferedReader( new InputStreamReader(HttpUtil.request(host.toString(), assign, EHttpMethod.GET))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // format HTTP Response to Assigned Info. assignedInfo = gson.fromJson(response.toString(), WeedAssign.class); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } finally { try { // close input stream. if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } // 2. Send cache file request on volume server FileBody fileBody = new FileBody(file, "text/plain"); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); StringBuffer uri = new StringBuffer(); uri.append("http://"); uri.append(assignedInfo.getPublicUrl()); uri.append("/"); uri.append(assignedInfo.getFid()); HttpPost post = new HttpPost(uri.toString()); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("fileBody", fileBody); post.setEntity(entity); try { // Add File char. String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); client.getConnectionManager().shutdown(); FileResult fileResult = gson.fromJson(response, FileResult.class); result.setFid(assignedInfo.getFid()); result.setSize(fileResult.getSize()); result.setStatus(true); result.setFileUrl(uri.toString()); return result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString()); } }
From source file:outfox.ynote.open.client.YNoteHttpUtils.java
/** * Do a http post with the multipart content type. This method is usually * used to upload the large size content, such as uploading a file. * * @param url/*from w w w .j av a 2 s . c o m*/ * @param formParams * @param accessor * @return * @throws IOException * @throws YNoteException */ public static HttpResponse doPostByMultipart(String url, Map<String, Object> formParams, OAuthAccessor accessor) throws IOException, YNoteException { HttpPost post = new HttpPost(url); // for multipart encoded post, only sign with the oauth parameters // do not sign the our form parameters Header oauthHeader = getAuthorizationHeader(url, OAuthMessage.POST, null, accessor); if (formParams != null) { // encode our ynote parameters MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("UTF-8")); for (Entry<String, Object> parameter : formParams.entrySet()) { if (parameter.getValue() instanceof File) { // deal with file particular entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else if (parameter.getValue() != null) { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName(YNoteConstants.ENCODING))); } } post.setEntity(entity); } post.addHeader(oauthHeader); HttpResponse response = client.execute(post); if ((response.getStatusLine().getStatusCode() / 100) != 2) { YNoteException e = wrapYNoteException(response); throw e; } return response; }
From source file:org.safegees.safegees.util.HttpUrlConnection.java
public static String performPostFileCall(String requestURL, String userCredentials, File file) { String response = null;/*from ww w . j ava 2 s.c o m*/ MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //reqEntity.addPart("avatar", new FileBody(file, ContentType.MULTIPART_FORM_DATA)); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(requestURL); httppost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials); httppost.addHeader("ContentType", "image/png"); httppost.addHeader("Referer", "https://safegees.appspot.com/v1/user/image/upload/"); httppost.addHeader("Origin", "https://safegees.appspot.com"); httppost.addHeader("Upgrade-Insecure-Requests", "1"); httppost.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); reqEntity.addBinaryBody("avatar", file, ContentType.create("image/png"), file.getName()); httppost.setEntity(reqEntity.build()); HttpResponse httpResponse = null; try { httpResponse = httpclient.execute(httppost); Log.e("IMAGE", httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.getStatusLine().getReasonPhrase()); //response = EntityUtils.toString(httpResponse.getEntity()); response = httpResponse.getStatusLine().getReasonPhrase(); } catch (IOException e) { e.printStackTrace(); } if (httpResponse.getStatusLine().getStatusCode() == 200) return response; return null; }
From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java
@Test public void testMultiPartRequest() throws IOException { TestHttpClient client = new TestHttpClient(); try {//from w w w .ja v a 2 s .co m String uri = DefaultServer.getDefaultServerURL() + "/servletContext/1"; HttpPost post = new HttpPost(uri); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, StandardCharsets.UTF_8); 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:ws.munday.youtubecaptionrate.WebRequest.java
public String PostFileWithBasicAuthorization(String uri, String filename, String Username, String Password) throws ClientProtocolException, IOException, URISyntaxException { _post = new HttpPost(uri); _post.addHeader("Authorization", "Basic " + Base64.encodeString(Username + ":" + Password)); File f = new File(new URI(filename)); MultipartEntity e = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fb = new FileBody(f); e.addPart("torrent_file", fb); StringBody sb = new StringBody("add-file"); e.addPart("action", sb); _post.setEntity(e);/*from w ww .ja v a 2 s. c o m*/ _response = _client.execute(_post); return GetResponseText(_response.getEntity().getContent()); }
From source file:com.jigarmjoshi.service.task.UploaderTask.java
private final boolean uploadEntryReport(Report entry) { if (entry == null || entry.getUploaded()) { return true; }//from ww w. j a v a 2 s .c om boolean resultFlag = false; try { Log.i(UploaderTask.class.getSimpleName(), "uploading " + entry.getImageFileName()); Bitmap bm = BitmapFactory.decodeFile(entry.getImageFileName()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bm.compress(CompressFormat.JPEG, 60, bos); byte[] data = bos.toByteArray(); HttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(this.serverUrl + "/uploadEntryRecord"); ByteArrayBody bab = new ByteArrayBody(data, "report.jpg"); // File file= new File("/mnt/sdcard/forest.png"); // FileBody bin = new FileBody(file); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("lat", new StringBody(Utility.encode(entry.getLat()))); reqEntity.addPart("lon", new StringBody(Utility.encode(entry.getLon()))); reqEntity.addPart("priority", new StringBody(Utility.encode(entry.getPriority()))); reqEntity.addPart("fileName", new StringBody(Utility.encode(entry.getImageFileName()))); reqEntity.addPart("reporterId", new StringBody(Utility.encode(entry.getId()))); reqEntity.addPart("uploaded", bab); postRequest.setEntity(reqEntity); HttpResponse response = httpClient.execute(postRequest); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder responseString = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { responseString = responseString.append(sResponse); } Log.i(UploaderTask.class.getSimpleName(), responseString.toString()); if ("SUCCESS".equalsIgnoreCase(responseString.toString())) { resultFlag = true; if (entry.getImageFileName() != null) { File imageFileToDelete = new File(entry.getImageFileName()); boolean deleted = imageFileToDelete.delete(); if (deleted) { Log.i(UploaderTask.class.getSimpleName(), "deleted = ?" + deleted); MediaScannerConnection.scanFile(context, new String[] { imageFileToDelete.getAbsolutePath() }, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { } }); } } } } catch (Exception ex) { Log.e(UploaderTask.class.getSimpleName(), "failed to upload", ex); resultFlag = false; } return resultFlag; }
From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java
public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_) throws ColdFusionException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol); HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_); MultipartEntityBuilder me = MultipartEntityBuilder.create(); me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); if (methodArgs_ != null) { for (String s : methodArgs_.keySet()) { Object obj = methodArgs_.get(s); if (obj != null) { if (obj instanceof String) { me.addTextBody(s, (String) obj); } else if (obj instanceof Integer) { me.addTextBody(s, ((Integer) obj).toString()); } else if (obj instanceof File) { me.addBinaryBody(s, (File) obj); } else if (obj instanceof IDocument) { me.addBinaryBody(s, ((IDocument) obj).getFile()); //me.addTextBody( "name", ((IDocument)obj).getFileName() ); //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType ); } else if (obj instanceof IDocument[]) { for (int i = 0; i < ((IDocument[]) obj).length; i++) { IDocument iDocument = ((IDocument[]) obj)[i]; me.addBinaryBody(s, iDocument.getFile()); //me.addTextBody("name", iDocument.getFileName() ); //me.addTextBody("contentType", iDocument.getContentType().contentType ); }/*from w w w. j a va 2s .co m*/ } else if (obj instanceof BufferedImage) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write((BufferedImage) obj, "jpg", baos); String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME); String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE)) .getExtension(); ContentType _contentType = ContentType.create(_mimeType); me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName); } else if (obj instanceof byte[]) { me.addBinaryBody(s, (byte[]) obj); } else if (obj instanceof Map) { ObjectMapper mapper = new ObjectMapper(); String _json = mapper.writeValueAsString(obj); me.addTextBody(s, _json); } } } } HttpEntity httpEntity = me.build(); method.setEntity(httpEntity); HttpResponse response = httpClient.execute(host, method);//, responseHandler); // Examine the response status if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Get hold of the response entity HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); //return inputStream; byte[] _body = IOUtils.toByteArray(inputStream); MultiValueMap _headers = new LinkedMultiValueMap(); for (Header header : response.getAllHeaders()) { if (header.getName().equalsIgnoreCase("content-length")) { _headers.add(header.getName(), header.getValue()); } else if (header.getName().equalsIgnoreCase("content-type")) { _headers.add(header.getName(), header.getValue()); // special condition to add zip to the file name. if (header.getValue().indexOf("text/") > -1) { //add nothing extra } else if (header.getValue().indexOf("zip") > -1) { if (methodArgs_.get("file") != null) { String _fileName = ((Document) methodArgs_.get("file")).getFileName(); _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + ".zip\""); } } else if (methodArgs_.get("file") != null) { String _fileName = ((Document) methodArgs_.get("file")).getFileName(); _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\""); } } } return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK); //Map json = (Map)deSerializeJson(inputStream); //return json; } } MultiValueMap _headers = new LinkedMultiValueMap(); _headers.add("Content-Type", "text/plain"); return new ResponseEntity(response.getStatusLine().toString(), _headers, org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
From source file:com.piusvelte.sonet.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Sonet.ACTION_UPLOAD.equals(action)) { if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE) && intent.hasExtra(Widgets.INSTANT_UPLOAD)) { String place = null; if (intent.hasExtra(Splace)) place = intent.getStringExtra(Splace); String tags = null; if (intent.hasExtra(Stags)) tags = intent.getStringExtra(Stags); // upload a photo Notification notification = new Notification(R.drawable.notification, "uploading photo", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading", PendingIntent.getActivity(PhotoUploadService.this, 0, (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);/*from w w w .j a v a 2s . c o m*/ (new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String response = null; if (params.length > 2) { Log.d(TAG, "upload file: " + params[2]); HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, mSonetCrypto.Decrypt(params[0]))); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(params[2]); ContentBody fileBody = new FileBody(file); entity.addPart(Ssource, fileBody); HttpClient httpClient = SonetHttpClient .getThreadSafeClient(getApplicationContext()); try { entity.addPart(Smessage, new StringBody(params[1])); if (params[3] != null) entity.addPart(Splace, new StringBody(params[3])); if (params[4] != null) entity.addPart(Stags, new StringBody(params[4])); httpPost.setEntity(entity); response = SonetHttpClient.httpResponse(httpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } return response; } @Override protected void onPostExecute(String response) { // notify photo success String message = getString(response != null ? R.string.success : R.string.failure); Notification notification = new Notification(R.drawable.notification, "photo upload " + message, System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", message, PendingIntent.getActivity(PhotoUploadService.this, 0, (Sonet.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification); stopSelfResult(mStartId); } }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE), intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags); } } } }
From source file:net.duckling.ddl.util.RESTClient.java
public JsonObject httpUpload(String url, String dataFieldName, byte[] data, List<NameValuePair> params) { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w. j av a 2 s. c o m HttpPost httppost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody(dataFieldName, data, ContentType.DEFAULT_BINARY, "tempfile"); for (NameValuePair hp : params) { builder.addPart(hp.getName(), new StringBody(hp.getValue(), ContentType.create("text/plain", Consts.UTF_8))); } HttpEntity reqEntity = builder.setCharset(CharsetUtils.get("UTF-8")).build(); httppost.setEntity(reqEntity); CloseableHttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } try { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(br); return je.getAsJsonObject(); } finally { response.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
From source file:com.shafiq.myfeedle.core.PhotoUploadService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); if (Myfeedle.ACTION_UPLOAD.equals(action)) { if (intent.hasExtra(Accounts.TOKEN) && intent.hasExtra(Statuses.MESSAGE) && intent.hasExtra(Widgets.INSTANT_UPLOAD)) { String place = null; if (intent.hasExtra(Splace)) place = intent.getStringExtra(Splace); String tags = null; if (intent.hasExtra(Stags)) tags = intent.getStringExtra(Stags); // upload a photo Notification notification = new Notification(R.drawable.notification, "uploading photo", System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", "uploading", PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification);/*from w ww . ja v a 2s. c om*/ (new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { String response = null; if (params.length > 2) { Log.d(TAG, "upload file: " + params[2]); HttpPost httpPost = new HttpPost(String.format(FACEBOOK_PHOTOS, FACEBOOK_BASE_URL, Saccess_token, mMyfeedleCrypto.Decrypt(params[0]))); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(params[2]); ContentBody fileBody = new FileBody(file); entity.addPart(Ssource, fileBody); HttpClient httpClient = MyfeedleHttpClient .getThreadSafeClient(getApplicationContext()); try { entity.addPart(Smessage, new StringBody(params[1])); if (params[3] != null) entity.addPart(Splace, new StringBody(params[3])); if (params[4] != null) entity.addPart(Stags, new StringBody(params[4])); httpPost.setEntity(entity); response = MyfeedleHttpClient.httpResponse(httpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } return response; } @Override protected void onPostExecute(String response) { // notify photo success String message = getString(response != null ? R.string.success : R.string.failure); Notification notification = new Notification(R.drawable.notification, "photo upload " + message, System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "photo upload", message, PendingIntent.getActivity(PhotoUploadService.this, 0, (Myfeedle.getPackageIntent(PhotoUploadService.this, About.class)), 0)); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFY_ID, notification); stopSelfResult(mStartId); } }).execute(intent.getStringExtra(Accounts.TOKEN), intent.getStringExtra(Statuses.MESSAGE), intent.getStringExtra(Widgets.INSTANT_UPLOAD), place, tags); } } } }