List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:org.opendatakit.aggregate.externalservice.OhmageJsonServer.java
/** * Uploads a set of submissions to the ohmage system. * * @throws IOException// w w w. j av a2 s . com * @throws ClientProtocolException * @throws ODKExternalServiceException * @throws URISyntaxException */ public void uploadSurveys(List<OhmageJsonTypes.Survey> surveys, Map<UUID, ByteArrayBody> photos, CallingContext cc) throws ClientProtocolException, IOException, ODKExternalServiceException, URISyntaxException { MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF_CHARSET); // emit the configured publisher parameters if the values are non-empty... String value; value = getOhmageCampaignUrn(); if (value != null && value.length() != 0) { StringBody campaignUrn = new StringBody(getOhmageCampaignUrn(), UTF_CHARSET); reqEntity.addPart("campaign_urn", campaignUrn); } value = getOhmageCampaignCreationTimestamp(); if (value != null && value.length() != 0) { StringBody campaignCreationTimestamp = new StringBody(getOhmageCampaignCreationTimestamp(), UTF_CHARSET); reqEntity.addPart("campaign_creation_timestamp", campaignCreationTimestamp); } value = getOhmageUsername(); if (value != null && value.length() != 0) { StringBody user = new StringBody(getOhmageUsername(), UTF_CHARSET); reqEntity.addPart("user", user); } value = getOhmageHashedPassword(); if (value != null && value.length() != 0) { StringBody hashedPassword = new StringBody(getOhmageHashedPassword(), UTF_CHARSET); reqEntity.addPart("passowrd", hashedPassword); } // emit the client identity and the json representation of the survey... StringBody clientParam = new StringBody(cc.getServerURL()); reqEntity.addPart("client", clientParam); StringBody surveyData = new StringBody(gson.toJson(surveys)); reqEntity.addPart("survey", surveyData); // emit the file streams for all the media attachments for (Entry<UUID, ByteArrayBody> entry : photos.entrySet()) { reqEntity.addPart(entry.getKey().toString(), entry.getValue()); } HttpResponse response = super.sendHttpRequest(POST, getServerUrl(), reqEntity, null, cc); String responseString = WebUtils.readResponse(response); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { throw new ODKExternalServiceCredentialsException( "failure from server: " + statusCode + " response: " + responseString); } else if (statusCode >= 300) { throw new ODKExternalServiceException( "failure from server: " + statusCode + " response: " + responseString); } }
From source file:com.cloudapp.rest.CloudApi.java
/** * Upload a file to the CloudApp servers. * //from ww w. jav a 2 s .c om * @param input * The inputstream that holds the content that should be stored on the server. * @param filename * The name of this file. i.e.: README.txt * @return A JSONObject with the returned output from the CloudApp servers. * @throws CloudApiException */ @SuppressWarnings("rawtypes") public JSONObject uploadFile(CloudAppInputStream stream) throws CloudApiException { HttpGet keyRequest = null; HttpPost uploadRequest = null; try { // Get a key for the file first. keyRequest = new HttpGet("http://my.cl.ly/items/new"); keyRequest.addHeader("Accept", "application/json"); // Execute the request. HttpResponse response = client.execute(keyRequest); int status = response.getStatusLine().getStatusCode(); if (status == 200) { String body = EntityUtils.toString(response.getEntity()); JSONObject json = new JSONObject(body); String url = json.getString("url"); JSONObject params = json.getJSONObject("params"); // From the API docs // Use this response to construct the upload. Each item in params becomes a // separate parameter you'll need to post to url. Send the file as the parameter // file. MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // Add all the plain parameters. Iterator keys = params.keys(); while (keys.hasNext()) { String key = (String) keys.next(); entity.addPart(key, new StringBody(params.getString(key))); } // Add the actual file. // We have to use the 'file' parameter for the S3 storage. entity.addPart("file", stream); uploadRequest = new HttpPost(url); uploadRequest.addHeader("Accept", "application/json"); uploadRequest.setEntity(entity); // Perform the actual upload. // uploadMethod.setFollowRedirects(true); response = client.execute(uploadRequest); status = response.getStatusLine().getStatusCode(); body = EntityUtils.toString(response.getEntity()); if (status == 200) { return new JSONObject(body); } throw new CloudApiException(status, "Was unable to upload the file to amazon:\n" + body, null); } throw new CloudApiException(500, "Was unable to retrieve a key from CloudApp to upload a file.", null); } catch (IOException e) { LOGGER.error("Error when trying to upload a file.", e); throw new CloudApiException(500, e.getMessage(), e); } catch (JSONException e) { LOGGER.error("Error when trying to convert the return output to JSON.", e); throw new CloudApiException(500, e.getMessage(), e); } finally { if (keyRequest != null) { keyRequest.abort(); } if (uploadRequest != null) { uploadRequest.abort(); } } }
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);// w w w. ja va2 s .co 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.rapidandroid.activity.FormReviewer.java
private void uploadFile(final String filename) { Toast.makeText(getApplicationContext(), FILE_UPLOAD_BEGUN, Toast.LENGTH_LONG).show(); Thread t = new Thread() { @Override/* w w w. j ava 2 s.c o m*/ public void run() { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(filename); HttpPost httpost = new HttpPost("http://192.168.7.127:8160/upload/upload"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; // Post, check and show the result (not really spectacular, // but works): response = httpclient.execute(httpost); Log.d("httpPost", "Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } success = true; } catch (Exception ex) { Log.d("FormReviewer", "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); success = false; } finally { mDebugHandler.post(mFinishUpload); } } }; t.start(); }
From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java
/** * uploads measurements data as a batch file * @param dbIterator/* w ww . j a v a2s .com*/ * @param latLonFormat * @param count * @param max * @return number of uploaded measurements */ private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count, int max) { writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")"); try { StringBuilder sb = new StringBuilder( "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n"); int thisBatchSize = 0; while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) { Measurement meassurement = dbIterator.next(); sb.append(latLonFormat.format(meassurement.getLat())).append(","); sb.append(latLonFormat.format(meassurement.getLon())).append(","); sb.append(meassurement.getMcc()).append(","); sb.append(meassurement.getMnc()).append(","); sb.append(meassurement.getLac()).append(","); sb.append(meassurement.getCellid()).append(","); sb.append(meassurement.getGsmSignalStrength()).append(","); sb.append(meassurement.getTimestamp()).append(","); sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(","); sb.append((int) meassurement.getSpeed()).append(","); sb.append((int) meassurement.getBearing()).append(","); sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : ""); sb.append("\n"); thisBatchSize++; } HttpResponse response = null; writeToLog("Upload request URL: " + httppost.getURI()); if (uploadThreadRunning) { String csv = sb.toString(); writeToLog("Upload data: " + csv); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("key", new StringBody(apiKey)); mpEntity.addPart("appId", new StringBody(appId)); mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()), "text/csv", MULTIPART_FILENAME)); ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); // reqEntity is the MultipartEntity instance mpEntity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(mpEntity.getContentEncoding()); bArrEntity.setContentType(mpEntity.getContentType()); httppost.setEntity(bArrEntity); response = httpclient.execute(httppost); if (response == null) { writeToLog("Upload: null HTTP-response"); throw new IllegalStateException("no HTTP-response from server"); } HttpEntity resEntity = response.getEntity(); writeToLog( "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine()); if (resEntity != null) { resEntity.consumeContent(); } if (response.getStatusLine() == null) { writeToLog(": " + "null HTTP-status-line"); throw new IllegalStateException("no HTTP-status returned"); } if (response.getStatusLine().getStatusCode() != 200) { throw new IllegalStateException( "HTTP-status code returned : " + response.getStatusLine().getStatusCode()); } } return count + thisBatchSize; } catch (IOException e) { throw new IllegalStateException("IO-Error: " + e.getMessage()); } }
From source file:org.coronastreet.gpxconverter.GarminForm.java
public void upload() { httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { try {//from w w w.j a v a 2s .c om HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#"); HttpResponse formResponse = httpClient.execute(get, localContext); HttpEntity formEntity = formResponse.getEntity(); EntityUtils.consume(formEntity); HttpPost request = new HttpPost( "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx"); request.setHeader("Referer", "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1"); request.setHeader("Accept", "text/html, application/xhtml+xml, */*"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); output = "[" + output + "]"; //OMG Garmin Sucks at JSON..... JSONObject uploadResponse = new JSONArray(output).getJSONObject(0); JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult"); try { int uploadID = importResult.getInt("uploadId"); log("Success! UploadID is " + uploadID); } catch (Exception e) { JSONArray failures = (JSONArray) importResult.get("failures"); JSONObject failure = (JSONObject) failures.get(0); JSONArray errorMessages = failure.getJSONArray("messages"); JSONObject errorMessage = errorMessages.getJSONObject(0); String content = errorMessage.getString("content"); log("Upload Failed! Error: " + content); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:com.pc.dailymile.DailyMileClient.java
public Long addNoteWithImage(String note, File imageFile) throws Exception { HttpPost request = new HttpPost(DailyMileUtil.ENTRIES_URL); HttpResponse response = null;//from w ww.j ava 2 s . co m try { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart("media[data]", new FileBody(imageFile, "image/jpeg")); mpEntity.addPart("media[type]", new StringBody("image")); mpEntity.addPart("message", new StringBody(note)); mpEntity.addPart("[share_on_services][facebook]", new StringBody("false")); mpEntity.addPart("[share_on_services][twitter]", new StringBody("false")); mpEntity.addPart("oauth_token", new StringBody(oauthToken)); request.setEntity(mpEntity); // send the request response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 401) { throw new RuntimeException( "unable to execute POST - url: " + DailyMileUtil.ENTRIES_URL + " body: " + note); } if (statusCode == 201) { Header loc = response.getFirstHeader("Location"); if (loc != null) { String locS = loc.getValue(); if (!StringUtils.isBlank(locS) && locS.matches(".*/[0-9]+$")) { try { return NumberUtils.createLong(locS.substring(locS.lastIndexOf("/") + 1)); } catch (NumberFormatException e) { return null; } } } } return null; } finally { try { if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } //EntityUtils.consume(response.getEntity()); } catch (IOException e) { // ignore } } }
From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {//from www . ja v a 2 s . co m HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URI url_orig; try { url_orig = new URI(url_string); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = url_orig.getHost(), authority = url_orig.getAuthority(); final String resolved_host = resolver != null ? resolver.resolve(host) : null; final String resolved_url = !isEmpty(resolved_host) ? url_string.replace("://" + host, "://" + resolved_host) : url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter parameter : params) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : params) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new TwitterException("Unsupported request method " + req.getMethod()); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (!isEmpty(resolved_host) && !resolved_host.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java
@Override public twitter4j.internal.http.HttpResponse request(final twitter4j.internal.http.HttpRequest req) throws TwitterException { try {// www .ja va2 s.co m HttpRequestBase commonsRequest; //final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URL url_orig = new URL(url_string); final String host = url_orig.getHost(); //final String resolved_host = resolver != null ? resolver.resolve(host) : null; //final String resolved_url = resolved_host != null ? url_string.replace("://" + host, "://" + resolved_host) // : url_string; final String resolved_url = url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; if (req.getParameters() != null) { for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { final ArrayList<NameValuePair> args = new ArrayList<NameValuePair>(); for (final HttpParameter parameter : req.getParameters()) { args.add(new BasicNameValuePair(parameter.getName(), parameter.getValue())); } if (args.size() > 0) { post.setEntity(new UrlEncodedFormEntity(args, "UTF-8")); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new AssertionError(); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } //if (resolved_host != null && !host.equals(resolved_host)) { //commonsRequest.addHeader("Host", host); //} final ApacheHttpClientHttpResponseImpl res = new ApacheHttpClientHttpResponseImpl( client.execute(commonsRequest), conf); final int statusCode = res.getStatusCode(); if (statusCode < OK && statusCode > ACCEPTED) throw new TwitterException(res.asString(), res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:com.openmeap.http.FileHandlingHttpRequestExecuterImpl.java
@Override public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException { // test to determine whether this is a file upload or not. Boolean isFileUpload = false; for (Object o : postParams.values()) { if (o instanceof File) { isFileUpload = true;/*from www.j av a2s . co m*/ break; } } if (isFileUpload) { try { HttpPost httpPost = new HttpPost(createUrl(url, getParams)); httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Object o : postParams.entrySet()) { Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o; if (entry.getValue() instanceof File) { // For File parameters File file = (File) entry.getValue(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(file.toURL().toString()); entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type)); } else { // For usual String parameters entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT))); } } httpPost.setEntity(entity); return execute(httpPost); } catch (Exception e) { throw new HttpRequestException(e); } } else { return super.postData(url, getParams, postParams); } }