List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:be.cytomine.client.Cytomine.java
public void uploadFile(String url, byte[] data) throws CytomineException { try {/*ww w.j a va 2 s . co m*/ HttpClient client = null; MultipartEntity entity = new MultipartEntity(); entity.addPart("files[]", new ByteArrayBody(data, new Date().getTime() + "file")); client = new HttpClient(publicKey, privateKey, getHost()); client.authorize("POST", url, entity.getContentType().getValue(), "application/json,*/*"); client.connect(getHost() + url); int code = client.post(entity); String response = client.getResponseData(); log.debug("response=" + response); client.disconnect(); JSONObject json = createJSONResponse(code, response); } catch (IOException e) { throw new CytomineException(e); } }
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException { HttpClient base = new DefaultHttpClient(); SSLContext ctx = null;// w w w.ja v a 2s. c om try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException ex) { log("exception in sendFormPost():"); } X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; try { ctx.init(null, new TrustManager[] { tm }, null); } catch (KeyManagementException ex) { log("exception in sendFormPost():"); } SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); HttpClient client = new DefaultHttpClient(ccm, base.getParams()); try { HttpPost post = new HttpPost(url); MultipartEntity multipart = new MultipartEntity(); for (String key : additionalParams.keySet()) multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8"))); if (proj != null) { multipart.addPart("uploaded_file", new FileBody(proj)); } post.setEntity(multipart); HttpResponse resp = client.execute(post); HttpEntity out = resp.getEntity(); InputStream in = out.getContent(); return FileUtils.readStream(in); } catch (Exception ex) { throw new IOException("POST failed", ex); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception ex) { // ignore } } }
From source file:org.mumod.util.HttpManager.java
private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam, File attachment) throws IOException, MustardException, AuthException { URI uri;/*from w ww. j a v a 2 s . c om*/ try { uri = new URI(url); } catch (URISyntaxException e) { throw new IOException("Invalid URL."); } if (MustardApplication.DEBUG) Log.d("HTTPManager", "Requesting " + uri); HttpPost post = new HttpPost(uri); HttpResponse response; // create the multipart request and add the parts to it MultipartEntity requestContent = new MultipartEntity(); long len = attachment.length(); InputStream ins = new FileInputStream(attachment); InputStreamEntity ise = new InputStreamEntity(ins, -1L); byte[] data = EntityUtils.toByteArray(ise); String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG; requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName())); if (params != null) { for (NameValuePair param : params) { len += param.getValue().getBytes().length; requestContent.addPart(param.getName(), new StringBody(param.getValue())); } } post.setEntity(requestContent); Log.d("Mustard", "Length: " + len); if (mHeaders != null) { Iterator<String> headKeys = mHeaders.keySet().iterator(); while (headKeys.hasNext()) { String key = headKeys.next(); post.setHeader(key, mHeaders.get(key)); } } if (consumer != null) { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } } try { mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); response = mClient.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); throw new IOException("HTTP protocol error."); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new AuthException(401, "Unauthorized: " + url); } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) { try { JSONObject json = null; try { json = new JSONObject(StreamUtil.toString(response.getEntity().getContent())); } catch (JSONException e) { throw new MustardException(998, "Non json response: " + e.toString()); } throw new MustardException(statusCode, json.getString("error")); } catch (IllegalStateException e) { throw new IOException("Could not parse error response."); } catch (JSONException e) { throw new IOException("Could not parse error response."); } } else if (statusCode != 200) { Log.e("Mustard", response.getStatusLine().getReasonPhrase()); throw new MustardException(999, "Unmanaged response code: " + statusCode); } return response.getEntity().getContent(); }
From source file:fm.smart.r1.activity.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String id) { String http_response = ""; int status_code = 0; HttpClient client = null;/*from w w w . java2 s . com*/ String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds"); String auth = Main.username(this) + ":" + Main.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
public String httpFileUpload(String filePath) { String sResponse = ""; HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(MyApp.HTTP_OCR_URL); MultipartEntity mpEntity = new MultipartEntity(); File file = new File(filePath); ContentBody cbFile = new FileBody(file, "image/png"); mpEntity.addPart("image", cbFile); httppost.setEntity(mpEntity);//from www. java 2s. c o m HttpResponse response = null; try { response = httpClient.execute(httppost); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { if (sResponse != null) { sResponse = sResponse.trim() + "\n" + line.trim(); } else { sResponse = line; } } Log.i(MyApp.TAG, sResponse); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } httpClient.getConnectionManager().shutdown(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return sResponse.trim(); }
From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java
/** * {@inheritDoc}//from w w w . j a va2s . c o m * * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#putInCollection(java.lang.String, * java.lang.String, java.io.InputStream) */ @Override public URI putInCollection(String collectionId, String fileName, InputStream in) { String url = UrlSupport.concat(new String[] { COLLECTION_PATH_PREFIX, collectionId }); HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(); ContentBody body = new InputStreamBody(in, fileName); entity.addPart("file", body); post.setEntity(entity); HttpResponse response = getResponse(post); try { if (response != null) { String content = EntityUtils.toString(response.getEntity()); return new URI(content); } } catch (Exception e) { throw new RuntimeException(e); } finally { closeConnection(response); } throw new RuntimeException("Unable to put file in collection"); }
From source file:org.mustard.util.HttpManager.java
private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam, File attachment) throws IOException, MustardException, AuthException { URI uri;// w ww. j a v a 2s. co m try { uri = new URI(url); } catch (URISyntaxException e) { throw new IOException("Invalid URL."); } if (MustardApplication.DEBUG) Log.d("HTTPManager", "Requesting " + uri); HttpPost post = new HttpPost(uri); HttpResponse response; // create the multipart request and add the parts to it MultipartEntity requestContent = new MultipartEntity(); long len = attachment.length(); InputStream ins = new FileInputStream(attachment); InputStreamEntity ise = new InputStreamEntity(ins, -1L); byte[] data = EntityUtils.toByteArray(ise); String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG; requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName())); if (params != null) { for (NameValuePair param : params) { len += param.getValue().getBytes().length; requestContent.addPart(param.getName(), new StringBody(param.getValue())); } } post.setEntity(requestContent); Log.d("Mustard", "Length: " + len); if (mHeaders != null) { Iterator<String> headKeys = mHeaders.keySet().iterator(); while (headKeys.hasNext()) { String key = headKeys.next(); post.setHeader(key, mHeaders.get(key)); } } if (consumer != null) { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { } catch (OAuthExpectationFailedException e) { } catch (OAuthCommunicationException e) { } } try { mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT); response = mClient.execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); throw new IOException("HTTP protocol error."); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new AuthException(401, "Unauthorized: " + url); } else if (statusCode == 403 || statusCode == 406) { try { JSONObject json = null; try { json = new JSONObject(StreamUtil.toString(response.getEntity().getContent())); } catch (JSONException e) { throw new MustardException(998, "Non json response: " + e.toString()); } throw new MustardException(statusCode, json.getString("error")); } catch (IllegalStateException e) { throw new IOException("Could not parse error response."); } catch (JSONException e) { throw new IOException("Could not parse error response."); } } else if (statusCode != 200) { Log.e("Mustard", response.getStatusLine().getReasonPhrase()); throw new MustardException(999, "Unmanaged response code: " + statusCode); } return response.getEntity().getContent(); }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type support forum And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIPublicToFile") public void testAddDocumentToAnAPISupportToFile() throws Exception { String fileNameAPIM626 = "APIM626.txt"; String docName = "APIM626PublisherTestHowTo-File-summary"; String docType = "support forum"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM626 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM626; String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag"; //Send Http Post request to add a new file HttpPost httppost = new HttpPost(addDocUrl); File file = new File(filePathAPIM626); FileBody fileBody = new FileBody(file, "text/plain"); //Create multipart entity to upload file as multipart file MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("docLocation", fileBody); multipartEntity.addPart("mode", new StringBody("")); multipartEntity.addPart("docName", new StringBody(docName)); multipartEntity.addPart("docUrl", new StringBody(docUrl)); multipartEntity.addPart("sourceType", new StringBody(sourceType)); multipartEntity.addPart("summary", new StringBody(summary)); multipartEntity.addPart("docType", new StringBody(docType)); multipartEntity.addPart("version", new StringBody(apiVersion)); multipartEntity.addPart("apiName", new StringBody(apiName)); multipartEntity.addPart("action", new StringBody("addDocumentation")); multipartEntity.addPart("provider", new StringBody(apiProvider)); multipartEntity.addPart("mimeType", new StringBody(mimeType)); multipartEntity.addPart("optionsRadios", new StringBody(docType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); multipartEntity.addPart("optionsRadios1", new StringBody(sourceType)); httppost.setEntity(multipartEntity); //Upload created file and validate HttpResponse response = httpClient.execute(httppost); HttpEntity entity = response.getEntity(); JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity)); assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API "); }
From source file:fm.smart.r1.CreateSoundActivity.java
public CreateSoundResult createSound(File file, String media_entity, String author, String author_url, String attribution_license_id, String item_id, String id, String to_record) { String http_response = ""; int status_code = 0; HttpClient client = null;/*from ww w . j a va 2s . c om*/ String type = "sentence"; String location = ""; try { client = new DefaultHttpClient(); if (sound_type.equals(Integer.toString(R.id.cue_sound))) { type = "item"; } HttpPost post = new HttpPost("http://api.smart.fm/" + type + "s/" + id + "/sounds.json"); String auth = LoginActivity.username(this) + ":" + LoginActivity.password(this); byte[] bytes = auth.getBytes(); post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes))); post.setHeader("Host", "api.smart.fm"); FileBody bin = new FileBody(file, "audio/amr"); StringBody media_entity_part = new StringBody(media_entity); StringBody author_part = new StringBody(author); StringBody author_url_part = new StringBody(author_url); StringBody attribution_license_id_part = new StringBody(attribution_license_id); StringBody id_part = new StringBody(id); StringBody api_key_part = new StringBody(Main.API_KEY); StringBody version_part = new StringBody("2"); StringBody text_part = new StringBody(to_record); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("sound[file]", bin); reqEntity.addPart("media_entity", media_entity_part); reqEntity.addPart("author", author_part); reqEntity.addPart("author_url", author_url_part); reqEntity.addPart("attribution_license_id", attribution_license_id_part); reqEntity.addPart(type + "_id", id_part); reqEntity.addPart("api_key", api_key_part); reqEntity.addPart("text", text_part); reqEntity.addPart("v", version_part); post.setEntity(reqEntity); Header[] array = post.getAllHeaders(); for (int i = 0; i < array.length; i++) { Log.d("DEBUG", array[i].toString()); } Log.d("CreateSoundActivity", "executing request " + post.getRequestLine()); HttpResponse response = client.execute(post); status_code = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); Log.d("CreateSoundActivity", "----------------------------------------"); Log.d("CreateSoundActivity", response.getStatusLine().toString()); array = response.getAllHeaders(); String header; for (int i = 0; i < array.length; i++) { header = array[i].toString(); if (header.equals("Location")) { location = header; } Log.d("CreateSoundActivity", header); } if (resEntity != null) { Log.d("CreateSoundActivity", "Response content length: " + resEntity.getContentLength()); Log.d("CreateSoundActivity", "Chunked?: " + resEntity.isChunked()); } long length = response.getEntity().getContentLength(); byte[] response_bytes = new byte[(int) length]; response.getEntity().getContent().read(response_bytes); Log.d("CreateSoundActivity", new String(response_bytes)); http_response = new String(response_bytes); if (resEntity != null) { resEntity.consumeContent(); } // HttpEntity entity = response1.getEntity(); } catch (IOException e) { /* Reset to Default image on any error. */ e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return new CreateSoundResult(status_code, http_response, location); }
From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java
public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId, boolean withGps) { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient httpClient = new DefaultHttpClient(params); try {/*from w w w . j a v a 2 s . c om*/ HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/"); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("app_id", new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8"))); multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8"))); // ? ? multipartEntity.addPart("parent_id", new StringBody(Integer.toString(parentId), Charset.forName("UTF-8"))); multipartEntity.addPart("reply_id", new StringBody(Integer.toString(replyId), Charset.forName("UTF-8"))); if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) { multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8"))); } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) { multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8"))); } else { multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8"))); } multipartEntity.addPart("account_id", new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_name", new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_avatar", new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8"))); if (withGps) { if (Statics.currentLocation != null) { multipartEntity.addPart("latitude", new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8"))); multipartEntity.addPart("longitude", new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8"))); } } multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8"))); if (!TextUtils.isEmpty(imagePath)) { multipartEntity.addPart("images", new FileBody(new File(imagePath))); } httpPost.setEntity(multipartEntity); String resp = httpClient.execute(httpPost, new BasicResponseHandler()); return JSONParser.parseMessagesString(resp).get(0); } catch (Exception e) { return null; } }