List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
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"); }/*w w w . j a v a 2s. c om*/ 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:net.asplode.tumblr.Post.java
/** * @param state/*from w ww.ja v a 2 s . co m*/ * True if the post should be private. False otherwise. * @throws UnsupportedEncodingException */ public void setPrivate(boolean state) throws UnsupportedEncodingException { if (state) entity.addPart("private", new StringBody("1")); }
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 w ww.j a v a2s . co 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); }
From source file:com.indigenedroid.app.volley.tools.MultiPartRequest.java
@Override public byte[] getBody() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); mEntity = new MultipartEntity(); FileInputStream fis;/*from w w w . j a v a 2s . c o m*/ try { fis = new FileInputStream(fileUploads.get("portrait_file")); InputStreamBody body = new InputStreamBody(fis, getFileName(fileUploads.get("portrait_file").getAbsolutePath())); mEntity.addPart("portrait_file", body); try { mEntity.addPart("token", new StringBody(stringUploads.get("token"))); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //HttpEntity entity = new FileEntity(fileUploads.get("portrait_file"), "application/octet-stream"); try { mEntity.writeTo(bos); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bos.toByteArray(); //return super.getBody(); }
From source file:com.parworks.androidlibrary.ar.ARSites.java
/** * Synchronously augment an image towards a list of sites * /*from w w w. j a v a 2s .c o m*/ * @param image * an inputstream containing the image * @return the augmented data */ public AugmentedData augmentImageGroup(List<String> sites, InputStream image) { Map<String, String> params = new HashMap<String, String>(); MultipartEntity imageEntity = new MultipartEntity(); InputStreamBody imageInputStreamBody = new InputStreamBody(image, "image"); imageEntity.addPart("image", imageInputStreamBody); for (String siteId : sites) { try { imageEntity.addPart("site", new StringBody(siteId)); } catch (UnsupportedEncodingException e) { throw new ARException(e); } } HttpUtils httpUtils = new HttpUtils(mApiKey, mTime, mSignature); HttpResponse serverResponse = httpUtils .doPost(HttpUtils.PARWORKS_API_BASE_URL + HttpUtils.AUGMENT_IMAGE_GROUP_PATH, imageEntity, params); HttpUtils.handleStatusCode(serverResponse.getStatusLine().getStatusCode()); ARResponseHandler responseHandler = new ARResponseHandlerImpl(); AugmentImageGroupResponse augmentImageGroupResponse = responseHandler.handleResponse(serverResponse, AugmentImageGroupResponse.class); if (augmentImageGroupResponse.getSuccess() == false) { throw new ARException( "Successfully communicated with the server, failed to augment the image. Perhaps the site does not exist or has no overlays."); } // List<AugmentedData> result = new ArrayList<AugmentedData>(); // for(SiteImageBundle bundle : augmentImageGroupResponse.getCandidates()) { // AugmentedData augmentedImage = null; // while (augmentedImage == null) { // augmentedImage = getAugmentResult(bundle.getSite(), bundle.getImgId()); // } // result.add(augmentedImage); // } List<AugmentedData> result = getAugmentedImageGroupResult(augmentImageGroupResponse.getSitesToCheck(), augmentImageGroupResponse.getImgId()); // combine different results AugmentedData finalData = null; for (AugmentedData data : result) { if (data.isLocalization()) { if (finalData == null) { finalData = data; } else { finalData.getOverlays().addAll(data.getOverlays()); } } } return finalData; }
From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java
public void execute() throws MojoExecutionException { this.getLog().info("Uploading project to BukkitDev"); final String gameVersion = this.getGameVersion(); final URIBuilder builder = new URIBuilder(); final MultipartEntity entity = new MultipartEntity(); HttpPost request;//from w w w.ja va2 s.c om // create the request builder.setScheme("http"); builder.setHost("dev.bukkit.org"); builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json"); try { entity.addPart("file_type", new StringBody(this.getFileType())); entity.addPart("name", new StringBody(this.project.getArtifact().getVersion())); entity.addPart("game_versions", new StringBody(gameVersion)); entity.addPart("change_log", new StringBody(this.changeLog)); entity.addPart("known_caveats", new StringBody(this.knownCaveats)); entity.addPart("change_markup_type", new StringBody(this.markupType)); entity.addPart("caveats_markup_type", new StringBody(this.markupType)); entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact()))); } catch (final UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage()); } // create the actual request try { request = new HttpPost(builder.build()); request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0"); request.setHeader("X-API-Key", this.key); request.setEntity(entity); } catch (final URISyntaxException exception) { throw new MojoExecutionException(exception.getMessage()); } this.getLog().debug(request.toString()); // send the request and handle any replies try { final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case 201: this.getLog().info("File uploaded successfully."); break; case 403: this.getLog().error( "You have not specifed your API key correctly or do not have permission to upload to that project."); break; case 404: this.getLog().error("Project was not found. Either it is specified wrong or been renamed."); break; case 422: this.getLog().error("There was an error in uploading the plugin"); this.getLog().debug(request.toString()); this.getLog().debug(EntityUtils.toString(response.getEntity())); break; default: this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode()); break; } } catch (final ClientProtocolException exception) { throw new MojoExecutionException(exception.getMessage()); } catch (final IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }
From source file:face4j.ResponderImpl.java
/** * @see {@link Responder#doPost(File, URI, List)} *///from w w w .j av a2 s. c o m public String doPost(final File file, final URI uri, final List<NameValuePair> params) throws FaceClientException, FaceServerException { try { final MultipartEntity entity = new MultipartEntity(); if (logger.isInfoEnabled()) { logger.info("Adding image entity, size: [{}] bytes", file.length()); } entity.addPart("image", new FileBody(file)); try { for (NameValuePair nvp : params) { entity.addPart(nvp.getName(), new StringBody(nvp.getValue())); } } catch (UnsupportedEncodingException uee) { logger.error("Error adding entity", uee); throw new FaceClientException(uee); } postMethod.setURI(uri); postMethod.setEntity(entity); final long start = System.currentTimeMillis(); final HttpResponse response = httpClient.execute(postMethod); if (logger.isDebugEnabled()) { logger.debug("POST took {} (ms)", (System.currentTimeMillis() - start)); } return checkResponse(response); } catch (IOException ioe) { logger.error("Error while POSTing to {} ", uri, ioe); throw new FaceClientException(ioe); } }
From source file:com.ushahidi.android.app.net.ReportsHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *//*from w w w . jav a 2s. c o m*/ public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException { log("PostFileUpload(): upload file to server."); apiUtils.updateDomain(); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("incident_title", new StringBody(params.get("incident_title"), Charset.forName("UTF-8"))); entity.addPart("incident_description", new StringBody(params.get("incident_description"), Charset.forName("UTF-8"))); entity.addPart("incident_date", new StringBody(params.get("incident_date"))); entity.addPart("incident_hour", new StringBody(params.get("incident_hour"))); entity.addPart("incident_minute", new StringBody(params.get("incident_minute"))); entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm"))); entity.addPart("incident_category", new StringBody(params.get("incident_category"))); entity.addPart("latitude", new StringBody(params.get("latitude"))); entity.addPart("longitude", new StringBody(params.get("longitude"))); entity.addPart("location_name", new StringBody(params.get("location_name"), Charset.forName("UTF-8"))); entity.addPart("person_first", new StringBody(params.get("person_first"), Charset.forName("UTF-8"))); entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8"))); entity.addPart("person_email", new StringBody(params.get("person_email"), Charset.forName("UTF-8"))); if (params.get("filename") != null) { if (!TextUtils.isEmpty(params.get("filename"))) { String filenames[] = params.get("filename").split(","); log("filenames " + ImageManager.getPhotoPath(context, filenames[0])); for (int i = 0; i < filenames.length; i++) { if (ImageManager.getPhotoPath(context, filenames[i]) != null) { File file = new File(ImageManager.getPhotoPath(context, filenames[i])); if (file.exists()) { entity.addPart("incident_photo[]", new FileBody(file)); } } } } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); int status = ApiUtils.extractPayloadJSON(GetText(serverInput)); if (status == 0) { return true; } return false; } } } catch (MalformedURLException ex) { log("PostFileUpload(): MalformedURLException", ex); return false; // fall through and return false } catch (IllegalArgumentException ex) { log("IllegalArgumentException", ex); // invalid URI return false; } catch (ConnectTimeoutException ex) { //connection timeout log("ConnectionTimeoutException"); return false; } catch (IOException e) { log("IOException", e); // timeout return false; } return false; }
From source file:com.jigarmjoshi.service.task.UploaderTask.java
private final boolean uploadEntryReport(Report entry) { if (entry == null || entry.getUploaded()) { return true; }//from w w w. j a v a2 s.c o m 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: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 w w .java2s .c om*/ _response = _client.execute(_post); return GetResponseText(_response.getEntity().getContent()); }