List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
From source file:com.cloudapp.rest.CloudApi.java
/** * Upload a file to the CloudApp servers. * /*ww w .j a v a 2s . 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:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type HowTo And" + " Source File through the publisher rest API ", dependsOnMethods = "testApiCreation") public void testAddDocumentToAnAPIHowToFile() throws Exception { String fileNameAPIM614 = "APIM614.txt"; String docName = "APIM614PublisherTestHowTo-File-summary"; String docType = "How To"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM614 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM614; ;/* ww w . j a v a 2 s . c o m*/ 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(filePathAPIM614); 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:org.megam.deccanplato.provider.box.handler.FileImpl.java
/** * @return// www . j a v a 2 s . c om */ private Map<String, String> upload() { Map<String, String> outMap = new HashMap<>(); final String BOX_UPLOAD = "/files/content"; Map<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN)); MultipartEntity entity = new MultipartEntity(); FileBody filename = new FileBody(new File(args.get(FILE_NAME))); FileBody filename1 = new FileBody(new File("/home/pandiyaraja/Documents/AMIs")); StringBody parent_id = null; try { parent_id = new StringBody(args.get(FOLDER_ID)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } entity.addPart("filename", filename); entity.addPart("parent_id", parent_id); TransportTools tools = new TransportTools(BOX_URI + BOX_UPLOAD, null, headerMap); tools.setFileEntity(entity); String responseBody = null; TransportResponse response = null; try { response = TransportMachinery.post(tools); responseBody = response.entityToString(); System.out.println("OUTPUT:" + responseBody); } catch (ClientProtocolException ce) { ce.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } outMap.put(OUTPUT, responseBody); return outMap; }
From source file:com.ibm.watson.developer_cloud.natural_language_classifier.v1.NaturalLanguageClassifier.java
/** * Sends data to create and train a classifier, and returns information about the new * classifier. The status has the value of `Training` when the operation is * successful, and might remain at this status for a while. * * @param name the classifier name * @param language IETF primary language for the classifier * @param csvTrainingData the CSV training data * @return the classifier/*w w w . ja v a 2 s .c om*/ * @see Classifier */ public Classifier createClassifier(final String name, final String language, final File csvTrainingData) { if (csvTrainingData == null || !csvTrainingData.exists()) throw new IllegalArgumentException("csvTrainingData can not be null or not be found"); JsonObject contentJson = new JsonObject(); contentJson.addProperty("language", language == null ? LANGUAGE_EN : language); if (name != null && !name.isEmpty()) { contentJson.addProperty("name", name); } try { MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("training_data", new FileBody(csvTrainingData)); reqEntity.addPart("training_metadata", new StringBody(contentJson.toString())); HttpRequestBase request = Request.Post("/v1/classifiers").withEntity(reqEntity).build(); HttpHost proxy = new HttpHost("10.100.1.124", 3128); ConnRouteParams.setDefaultProxy(request.getParams(), proxy); HttpResponse response = execute(request); return ResponseUtil.getObject(response, Classifier.class); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:info.ajaxplorer.client.http.RestRequest.java
private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName, AjxpFileBody fileBody) throws Exception { URI originalUri = new URI(uri.toString()); if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) { uri = new URI( uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN())); }//w w w . ja va2s. co m //Log.d("RestRequest", "Issuing request : " + uri.toString()); HttpResponse response = null; try { HttpRequestBase request; if (postParameters != null || file != null) { request = new HttpPost(); if (file != null) { if (fileBody == null) { if (fileName == null) fileName = file.getName(); fileBody = new AjxpFileBody(file, fileName); ProgressListener origPL = this.uploadListener; Map<String, String> caps = RestStateHolder.getInstance().getServer() .getRemoteCapacities(this); this.uploadListener = origPL; int maxUpload = 0; if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT)) maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT)); maxUpload = Math.min(maxUpload, 60000000); if (maxUpload > 0 && maxUpload < file.length()) { fileBody.chunkIntoPieces(maxUpload); if (uploadListener != null) { uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks()); } } } else { if (uploadListener != null) { uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks()); } } MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); reqEntity.addPart("userfile_0", fileBody); if (fileName != null && !EncodingUtils .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) { reqEntity.addPart("urlencoded_filename", new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8"))); } if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) { reqEntity.addPart("appendto_urlencoded_part", new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8"))); } if (postParameters != null) { Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue())); } } if (uploadListener != null) { CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity( reqEntity, uploadListener); ((HttpPost) request).setEntity(countingEntity); } else { ((HttpPost) request).setEntity(reqEntity); } } else { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size()); Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else { request = new HttpGet(); } request.setURI(uri); if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) { request.addHeader("Ajxp-Force-Login", "true"); } response = httpClient.executeInContext(request); if (isAuthenticationRequested(response)) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH); this.discardResponse(response); this.authenticate(); if (loginStateChanged) { // RELOAD loginStateChanged = false; sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA); if (fileBody != null) fileBody.resetChunkIndex(); return this.issueRequest(originalUri, postParameters, file, fileName, fileBody); } } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) { this.discardResponse(response); this.issueRequest(originalUri, postParameters, file, fileName, fileBody); } } catch (ClientProtocolException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } catch (IOException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } catch (AuthenticationException e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); throw e; } catch (Exception e) { sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage()); e.printStackTrace(); } finally { uploadListener = null; } return response; }
From source file:com.qsoft.components.gallery.utils.GalleryUtils.java
private static MultipartEntity addParamsForUpload(File file, String imageType, String imageName, Long equipmentId, Long userId, String locationDTO, Long equipmentHistoryId) throws UnsupportedEncodingException { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart(ConstantImage.IMAGE_FILE, new FileBody(file)); mpEntity.addPart(ConstantImage.IMAGE_TYPE, new StringBody(imageType.toUpperCase())); mpEntity.addPart(ConstantImage.IMAGE_NAME, new StringBody(imageName.toUpperCase())); if (equipmentId != null) { mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString())); }/*from w w w .jav a 2 s . c om*/ if (userId != null) { mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString())); } if (equipmentHistoryId != null) { mpEntity.addPart(ConstantImage.EQUIPMENTHISTORY_ID, new StringBody(equipmentHistoryId.toString())); } mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(locationDTO)); return mpEntity; }
From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java
private INTYPE doRequest() throws IOException { HttpClient client = new ContentEncodingHttpClient(); HttpUriRequest req;/*from ww w . j a v a 2 s . co m*/ JAXBContext context; Document outDocument = null; try { context = getJAXBContext(); } catch (JAXBException jaxb) { throw new IOException("Unable to acquire JAXB context: " + jaxb.getMessage()); } try { if (requestMethod == RequestMethod.POST) { if (this.sendingObject == null) throw new NullPointerException("requestDocument is null yet required for this type of query"); // Create a new POST request HttpPost post = new HttpPost(url); // Make it a multipart post MultipartEntity postEntity = new MultipartEntity(); req = post; // create an XML document from the given objects outDocument = marshallToDocument(context, sendingObject, getNamespacePrefixMapper()); // add it to the http post request XMLBody xmlb = new XMLBody(outDocument, "application/tellervo+xml", null); postEntity.addPart("xmlrequest", xmlb); postEntity.addPart("traceback", new StringBody(getStackTrace())); post.setEntity(postEntity); } else { // well, that's nice and easy req = new HttpGet(url); } // debug this transaction... TransactionDebug.sent(outDocument, noun); // load cookies ((AbstractHttpClient) client).setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); req.setHeader("User-Agent", "Tellervo WSI " + Build.getUTF8Version() + " (" + clientModuleVersion + "; ts " + Build.getCompleteVersionNumber() + ")"); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } // create a responsehandler JaxbResponseHandler<INTYPE> responseHandler = new JaxbResponseHandler<INTYPE>(context, receivingObjectClass); // set the schema we validate against responseHandler.setValidateSchema(getValidationSchema()); // execute the actual http query INTYPE inObject = null; try { inObject = client.execute(req, responseHandler); } catch (EOFException e4) { log.debug("Caught EOFException"); } TransactionDebug.received(inObject, noun, context); // save our cookies? WSCookieStoreHandler.getCookieStore().fromCookieStore(((AbstractHttpClient) client).getCookieStore()); // ok, now inspect the document we got back //TellervoDocumentInspector inspector = new TellervoDocumentInspector(inDocument); // Verify our document based on schema validity //inspector.validate(); // Verify our document structure, throw any exceptions! //inspector.verifyDocument(); return inObject; } catch (UnknownHostException e) { throw new IOException("The URL of the server you have specified is unknown"); } catch (HttpResponseException hre) { if (hre.getStatusCode() == 404) { throw new IOException("The URL of the server you have specified is unknown"); } BugReport bugs = new BugReport(hre); bugs.addDocument("sent.xml", outDocument); new BugDialog(bugs); throw new IOException("The server returned a protocol error " + hre.getStatusCode() + ": " + hre.getLocalizedMessage()); } catch (IllegalStateException ex) { throw new IOException("Webservice URL must be a full URL qualified with a communications protocol.\n" + "Tellervo currently supports http:// and https://."); } catch (ResponseProcessingException rspe) { Throwable cause = rspe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = rspe.getNonvalidatingDocument(); File invalidFile = rspe.getInvalidFile(); if (outDocument != null) bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw rspe; } catch (XMLParsingException xmlpe) { Throwable cause = xmlpe.getCause(); BugReport bugs = new BugReport(cause); Document invalidDoc = xmlpe.getNonvalidatingDocument(); File invalidFile = xmlpe.getInvalidFile(); bugs.addDocument("sent.xml", outDocument); if (invalidDoc != null) bugs.addDocument("recv-nonvalid.xml", invalidDoc); if (invalidFile != null) bugs.addDocument("recv-malformed.xml", invalidFile); new BugDialog(bugs); XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true); // it's probably an ioexception... if (cause instanceof IOException) throw (IOException) cause; throw xmlpe; } catch (IOException ioe) { throw ioe; } catch (Exception uhe) { BugReport bugs = new BugReport(uhe); bugs.addDocument("sent.xml", outDocument); /* // MalformedDocs are handled automatically by BugReport class if(!(uhe instanceof MalformedDocumentException) && inDocument != null) bugs.addDocument("received.xml", inDocument); */ new BugDialog(bugs); throw new IOException("Exception " + uhe.getClass().getName() + ": " + uhe.getLocalizedMessage()); } finally { //? } }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doMultipart(HttpPost method, HttpServletRequest req) throws ServletException, FileUploadException, UnsupportedEncodingException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(TEMP_DIR); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req); MultipartEntity entity = new MultipartEntity(); for (FileItem fItem : fileItems) { if (fItem.isFormField()) { LOG.log(Level.INFO, "Form field {0}", fItem.getName()); StringBody part = new StringBody(fItem.getFieldName()); entity.addPart(fItem.getFieldName(), part); } else {//from www . jav a2 s .c o m LOG.log(Level.INFO, "File item {0}", fItem.getName()); InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(), fItem.getContentType()); entity.addPart(fItem.getFieldName(), file); } } method.setEntity(entity); }
From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token.//from w w w . j a v a 2s . c om */ @Override protected Uri doInBackground(Void... params) { // Leave room in the progressbar for uploading determineProgressGoal(); mProgressAdmin.setUpload(true); // Build GPX file Uri gpxFile = exportGpx(); if (isCancelled()) { String text = mContext.getString(R.string.ticker_failed) + " \"http://api.gobreadcrumbs.com/v1/tracks\" " + mContext.getString(R.string.error_buildxml); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Fail to execute request due to canceling"), text); } // Collect GPX Import option params mActivityId = null; mBundleId = null; mDescription = null; mIsPublic = null; Uri metadataUri = Uri.withAppendedPath(mTrackUri, "metadata"); Cursor cursor = null; try { cursor = mContext.getContentResolver().query(metadataUri, new String[] { MetaData.KEY, MetaData.VALUE }, null, null, null); if (cursor.moveToFirst()) { do { String key = cursor.getString(0); if (BreadcrumbsTracks.ACTIVITY_ID.equals(key)) { mActivityId = cursor.getString(1); } else if (BreadcrumbsTracks.BUNDLE_ID.equals(key)) { mBundleId = cursor.getString(1); } else if (BreadcrumbsTracks.DESCRIPTION.equals(key)) { mDescription = cursor.getString(1); } else if (BreadcrumbsTracks.ISPUBLIC.equals(key)) { mIsPublic = cursor.getString(1); } } while (cursor.moveToNext()); } } finally { if (cursor != null) { cursor.close(); } } if ("-1".equals(mActivityId)) { String text = "Unable to upload without a activity id stored in meta-data table"; IllegalStateException e = new IllegalStateException(text); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, text); } int statusCode = 0; String responseText = null; Uri trackUri = null; HttpEntity responseEntity = null; try { if ("-1".equals(mBundleId)) { mBundleDescription = "";//mContext.getString(R.string.breadcrumbs_bundledescription); mBundleName = mContext.getString(R.string.app_name); mBundleId = createOpenGpsTrackerBundle(); } String gpxString = XmlCreator .convertStreamToString(mContext.getContentResolver().openInputStream(gpxFile)); HttpPost method = new HttpPost("http://api.gobreadcrumbs.com:80/v1/tracks"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } // Build the multipart body with the upload data MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("import_type", new StringBody("GPX")); //entity.addPart("gpx", new FileBody(gpxFile)); entity.addPart("gpx", new StringBody(gpxString)); entity.addPart("bundle_id", new StringBody(mBundleId)); entity.addPart("activity_id", new StringBody(mActivityId)); entity.addPart("description", new StringBody(mDescription)); // entity.addPart("difficulty", new StringBody("3")); // entity.addPart("rating", new StringBody("4")); entity.addPart("public", new StringBody(mIsPublic)); method.setEntity(entity); // Execute the POST to OpenStreetMap mConsumer.sign(method); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "HTTP Method " + method.getMethod()); Log.d(TAG, "URI scheme " + method.getURI().getScheme()); Log.d(TAG, "Host name " + method.getURI().getHost()); Log.d(TAG, "Port " + method.getURI().getPort()); Log.d(TAG, "Request path " + method.getURI().getPath()); Log.d(TAG, "Consumer Key: " + mConsumer.getConsumerKey()); Log.d(TAG, "Consumer Secret: " + mConsumer.getConsumerSecret()); Log.d(TAG, "Token: " + mConsumer.getToken()); Log.d(TAG, "Token Secret: " + mConsumer.getTokenSecret()); Log.d(TAG, "Execute request: " + method.getURI()); for (Header header : method.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(method); mProgressAdmin.addUploadProgress(); statusCode = response.getStatusLine().getStatusCode(); responseEntity = response.getEntity(); InputStream stream = responseEntity.getContent(); responseText = XmlCreator.convertStreamToString(stream); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Upload Response: " + responseText); } Pattern p = Pattern.compile(">([0-9]+)</id>"); Matcher m = p.matcher(responseText); if (m.find()) { Integer trackId = Integer.valueOf(m.group(1)); trackUri = Uri.parse("http://api.gobreadcrumbs.com/v1/tracks/" + trackId + "/placemarks.gpx"); for (File photo : mPhotoUploadQueue) { uploadPhoto(photo, trackId); } } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), e, "A problem during communication"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } if (statusCode == 200 || statusCode == 201) { if (trackUri == null) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Unable to retrieve URI from response"), responseText); } } else { //mAdapter.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_upload), new IOException("Status code: " + statusCode), responseText); } return trackUri; }
From source file:gov.medicaid.screening.dao.impl.BaseDAO.java
/** * Posts the Datagrid form./*from ww w. j a v a 2s. c o m*/ * * @param hostId * the unique host identifier * @param client * the client to use * @param httppost * the postback resource * @param postFragments * the fragments to include * @param multipartForm * to use multipart or regular form entity * @return the response entity * @throws ClientProtocolException * for protocol connection error * @throws IOException * for IO related errors * @throws ServiceException * if the post execution leads to an error */ protected HttpEntity postForm(String hostId, DefaultHttpClient client, HttpPost httppost, String[][] postFragments, boolean multipartForm) throws ClientProtocolException, IOException, ServiceException { HttpEntity entity = null; if (multipartForm) { MultipartEntity multiPartEntity = new MultipartEntity(); for (String[] params : postFragments) { multiPartEntity.addPart(params[0], new StringBody(params[1])); } entity = multiPartEntity; } else { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (String[] params : postFragments) { parameters.add(new BasicNameValuePair(params[0], params[1])); } entity = new UrlEncodedFormEntity(parameters); } httppost.setEntity(entity); HttpResponse postResponse = client.execute(httppost); verifyAndAuditCall(hostId, postResponse); return postResponse.getEntity(); }