List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
From source file:palamarchuk.smartlife.app.fragments.ProfileFragment.java
private void attachCardQuery(String cardNumber, String cardPin) { final QueryMaster.OnCompleteListener onCompleteListener = new QueryMaster.OnCompleteListener() { @Override/* w ww . j a va 2s.com*/ public void complete(String serverResponse) { // QueryMaster.alert(getActivity(), serverResponse); try { JSONObject json = new JSONObject(serverResponse); if (QueryMaster.isSuccess(json)) { FragmentHelper.updateFragment(getFragmentManager()); QueryMaster.alert(getActivity(), R.string.bonuses_was_added_from_card); } else { QueryMaster.toast(getActivity(), json.getString("message")); } } catch (JSONException e) { e.printStackTrace(); QueryMaster.alert(getActivity(), QueryMaster.SERVER_RETURN_INVALID_DATA); } } @Override public void error(int errorCode) { QueryMaster.alert(getActivity(), QueryMaster.ERROR_MESSAGE); } }; MultipartEntity entity = new MultipartEntity(); try { entity.addPart("card_number", new StringBody(cardNumber)); entity.addPart("pin", new StringBody(cardPin)); entity.addPart("token", new StringBody(((FragmentHolderActivity) getActivity()).getDeviceToken())); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } QueryMaster queryMaster = new QueryMaster(getActivity(), ServerRequest.ATTACH_CARD, QueryMaster.QUERY_POST, entity); queryMaster.setProgressDialog(); queryMaster.setOnCompleteListener(onCompleteListener); queryMaster.start(); }
From source file:org.fedoraproject.eclipse.packager.bodhi.api.BodhiClient.java
@Override public BodhiUpdateResponse createNewUpdate(String[] builds, String release, String type, String request, String bugs, String notes, String csrfToken, boolean suggestReboot, boolean enableKarmaAutomatism, int stableKarmaThreshold, int unstableKarmaThreshold, boolean closeBugsWhenStable) throws BodhiClientException { try {//from w w w .ja v a 2 s . c o m HttpPost post = new HttpPost(getPushUpdateUrl()); post.addHeader(ACCEPT_HTTP_HEADER_NAME, MIME_JSON); StringBuffer buildsNVR = new StringBuffer(); for (int i = 0; i < (builds.length - 1); i++) { buildsNVR.append(builds[i]); buildsNVR.append(BUILDS_DELIMITER); } buildsNVR.append(builds[(builds.length - 1)]); String buildsParamValue = buildsNVR.toString(); // Construct the multipart POST request body. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(BUILDS_PARAM_NAME, new StringBody(buildsParamValue)); reqEntity.addPart(TYPE_PARAM_NAME, new StringBody(type)); reqEntity.addPart(REQUEST_PARAM_NAME, new StringBody(request)); reqEntity.addPart(BUGS_PARAM_NAME, new StringBody(bugs)); reqEntity.addPart(CSRF_PARAM_NAME, new StringBody(csrfToken)); reqEntity.addPart(AUTOKARMA_PARAM_NAME, new StringBody(String.valueOf(enableKarmaAutomatism))); reqEntity.addPart(NOTES_PARAM_NAME, new StringBody(notes)); reqEntity.addPart(SUGGEST_REBOOT, new StringBody(String.valueOf(suggestReboot))); reqEntity.addPart(STABLE_KARMA, new StringBody(String.valueOf(stableKarmaThreshold))); reqEntity.addPart(UNSTABLE_KARMA, new StringBody(String.valueOf(unstableKarmaThreshold))); reqEntity.addPart(CLOSE_BUGS_WHEN_STABLE, new StringBody(String.valueOf(closeBugsWhenStable))); post.setEntity(reqEntity); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new BodhiClientException(NLS.bind("{0} {1}", response.getStatusLine().getStatusCode(), //$NON-NLS-1$ response.getStatusLine().getReasonPhrase()), response); } else { String rawJsonString = ""; //$NON-NLS-1$ if (resEntity != null) { try { rawJsonString = parseResponse(resEntity); } catch (IOException e) { // ignore } EntityUtils.consume(resEntity); // clean up resources } // log JSON string if in debug mode if (PackagerPlugin.inDebugMode()) { FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance(); logger.logInfo(NLS.bind(BodhiText.BodhiClient_rawJsonStringMsg, rawJsonString)); } // deserialize the result from the JSON response GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); BodhiUpdateResponse result = gson.fromJson(rawJsonString, BodhiUpdateResponse.class); return result; } } catch (IOException e) { throw new BodhiClientException(e.getMessage(), e); } }
From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java
@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type Sample SDK And" + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIHowToFile") public void testAddDocumentToAnAPISDKToFile() throws Exception { String fileNameAPIM622 = "APIM622.txt"; String docName = "APIM622PublisherTestHowTo-File-summary"; String docType = "samples"; String sourceType = "file"; String summary = "Testing"; String mimeType = "text/plain"; String docUrl = "http://"; String filePathAPIM622 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM622; 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(filePathAPIM622); 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.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Check if upload file has already been uploaded. Do nothing, if file is * missing.//ww w.j a v a 2 s .c o m * * @throws UploadFailedException * If something went wrong sending/receiving the request to/from * the lookaside cache. * @throws FileAvailableInLookasideCacheException * If the upload candidate file is already present in the * lookaside cache. */ private void checkSourceAvailable() throws FileAvailableInLookasideCacheException, UploadFailedException { HttpClient client = getClient(); try { String uploadURI = null; uploadURI = this.projectRoot.getLookAsideCache().getUploadUrl().toString(); assert uploadURI != null; if (fedoraSslEnabled) { // user requested Fedora SSL enabled client try { client = fedoraSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } else if (trustAllSSLEnabled) { // use accept all SSL enabled client try { client = trustAllSslEnable(client); } catch (GeneralSecurityException e) { throw new UploadFailedException(e.getMessage(), e); } } HttpPost post = new HttpPost(uploadURI); // provide hint which URL is going to be used FedoraPackagerLogger logger = FedoraPackagerLogger.getInstance(); logger.logDebug(NLS.bind(FedoraPackagerText.UploadSourceCommand_usingUploadURLMsg, uploadURI)); // Construct the multipart POST request body. MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(FILENAME_PARAM_NAME, new StringBody(fileToUpload.getName())); reqEntity.addPart(PACKAGENAME_PARAM_NAME, new StringBody(projectRoot.getSpecfileModel().getName())); reqEntity.addPart(CHECKSUM_PARAM_NAME, new StringBody(SourcesFile.calculateChecksum(fileToUpload))); post.setEntity(reqEntity); HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); int returnCode = response.getStatusLine().getStatusCode(); if (returnCode != HttpURLConnection.HTTP_OK) { throw new UploadFailedException(response.getStatusLine().getReasonPhrase(), response); } else { String resString = ""; //$NON-NLS-1$ if (resEntity != null) { try { resString = parseResponse(resEntity); } catch (IOException e) { // ignore } EntityUtils.consume(resEntity); // clean up resources } // If this file has already been uploaded bail out if (resString.toLowerCase().equals(RESOURCE_AVAILABLE)) { throw new FileAvailableInLookasideCacheException(fileToUpload.getName()); } else if (resString.toLowerCase().equals(RESOURCE_MISSING)) { // check passed return; } else { // something is fishy throw new UploadFailedException(FedoraPackagerText.somethingUnexpectedHappenedError); } } } catch (IOException e) { throw new UploadFailedException(e.getMessage(), e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java
public static JSONObject CallFunction(String url, String[] paramNames, String[] paramVals, Context context) { JSONObject json = new JSONObject(); SchemeRegistry supportedSchemes = new SchemeRegistry(); SSLSocketFactory sf = getSocketFactory(DEBUG); // TODO we make assumptions about ports. supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); supportedSchemes.register(new Scheme("https", sf, 443)); HttpParams http_params = new BasicHttpParams(); ClientConnectionManager ccm = new ThreadSafeClientConnManager(http_params, supportedSchemes); // HttpParams http_params = httpclient.getParams(); http_params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpConnectionParams.setConnectionTimeout(http_params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(http_params, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(ccm, http_params); if (paramNames == null) { paramNames = new String[0]; }/*from ww w . jav a 2 s.co m*/ if (paramVals == null) { paramVals = new String[0]; } if (paramNames.length != paramVals.length) { Log.w(TAG, "Incompatible number of param names and values, bailing on upload!"); return null; } SortedMap<String, String> sig_params = new TreeMap<String, String>(); HttpResponse response = null; HttpPost httppost = null; Log.d(TAG, "HTTP POST URL: " + url); try { httppost = new HttpPost(url); } catch (IllegalArgumentException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return json; } try { File file = null; // If this is a POST call, then it is a file upload. Check to see if // a // filename is given, and if so, open that file. // Get the title of the photo being uploaded so we can pass it into // the // MultipartEntityMonitored class to be broadcast for progress // updates. String title = ""; for (int i = 0; i < paramNames.length; ++i) { if (paramNames[i].equals("title")) { title = paramVals[i]; } else if (paramNames[i].equals("filename")) { file = new File(paramVals[i]); continue; } sig_params.put(paramNames[i], paramVals[i]); } MultipartEntityMonitored mp_entity = new MultipartEntityMonitored(context, title); if (file != null) { mp_entity.addPart("userfile", new FileBody(file)); } for (Map.Entry<String, String> entry : sig_params.entrySet()) { mp_entity.addPart(entry.getKey(), new StringBody(entry.getValue())); } httppost.setEntity(mp_entity); response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String content = convertStreamToString(resEntity.getContent()); if (response.getStatusLine().getStatusCode() == 200) { try { json = new JSONObject(content.toString()); } catch (JSONException e1) { Log.w(TAG, "Response 200 received but invalid JSON."); json.put("fail", e1.getMessage()); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } else { Log.w(TAG, "File upload failed with response code:" + response.getStatusLine().getStatusCode()); json.put("fail", response.getStatusLine().getReasonPhrase()); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } else { Log.w(TAG, "Response does not contain a valid HTTP entity."); if (DEBUG) Log.d(TAG, "HTTP POST returned status code: " + response.getStatusLine()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (IllegalStateException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (IllegalArgumentException e) { try { json.put("fail", e.getMessage()); } catch (JSONException e1) { } e.printStackTrace(); } catch (JSONException e) { } httpclient.getConnectionManager().shutdown(); return json; }
From source file:com.cianmcgovern.android.ShopAndShare.Share.java
/** * Uploads the text file specified by filename * //from w w w .ja va 2 s. c o m * @param instance * The results instance to use * @param location * The location as specified by the user * @param store * The store as specified by the user * @return Response message from server * @throws ClientProtocolException * @throws IOException */ private String upload(Results instance, String location, String store) throws ClientProtocolException, IOException { Log.v(Constants.LOG_TAG, "Inside upload"); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String filename = Results.getInstance().toFile(); HttpPost httpPost = new HttpPost(Constants.FULL_URL); File file = new File(filename); MultipartEntity entity = new MultipartEntity(); ContentBody cb = new FileBody(file, "plain/text"); entity.addPart("inputfile", cb); ContentBody cbLocation = new StringBody(location); entity.addPart("location", cbLocation); ContentBody cbStore = new StringBody(store); entity.addPart("store", cbStore); httpPost.setEntity(entity); Log.v(Constants.LOG_TAG, "Sending post"); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String message = EntityUtils.toString(resEntity); Log.v(Constants.LOG_TAG, "Response from upload is: " + message); resEntity.consumeContent(); httpClient.getConnectionManager().shutdown(); file.delete(); return message; }
From source file:org.fcrepo.integration.api.FedoraDatastreamsIT.java
License:asdf
@Test public void testRetrieveMultipartDatastreams() throws Exception { final HttpPost objMethod = postObjMethod("FedoraDatastreamsTest9"); assertEquals(201, getStatus(objMethod)); final HttpPost post = new HttpPost(serverAddress + "objects/FedoraDatastreamsTest9/datastreams/"); final MultipartEntity multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("ds1", new StringBody("asdfg")); multiPartEntity.addPart("ds2", new StringBody("qwerty")); post.setEntity(multiPartEntity);/* www . j a v a2 s .c o m*/ final HttpResponse postResponse = client.execute(post); assertEquals(201, postResponse.getStatusLine().getStatusCode()); // TODO: we should actually evaluate the multipart response for the // things we're expecting final HttpGet getDSesMethod = new HttpGet( serverAddress + "objects/FedoraDatastreamsTest9/datastreams/__content__"); final HttpResponse response = client.execute(getDSesMethod); assertEquals(200, response.getStatusLine().getStatusCode()); final String content = EntityUtils.toString(response.getEntity()); assertTrue("Didn't find the first datastream!", compile("asdfg", DOTALL).matcher(content).find()); assertTrue("Didn't find the second datastream!", compile("qwerty", DOTALL).matcher(content).find()); }
From source file:org.deviceconnect.android.profile.restful.test.NormalFileDescriptorProfileTestCase.java
/** * ????.//from w w w. j av a 2s . com * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/write?deviceid=xxxx&mediaid=xxxx&position=xxx * Entity: "test" * </pre> * <pre> * ?? * result?0??????? * </pre> */ public void testWrite002() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/" + FileDescriptorProfileConstants.PROFILE_NAME); builder.append("/" + FileDescriptorProfileConstants.ATTRIBUTE_WRITE); builder.append("?"); builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId()); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_PATH + "=test.txt"); builder.append("&"); builder.append(FileDescriptorProfileConstants.PARAM_POSITION + "=0"); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken()); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("media", new StringBody("test")); HttpPut request = new HttpPut(builder.toString()); request.addHeader("Content-Disposition", "form-data; name=\"media\"; filename=\"test.txt\""); request.setEntity(entity); JSONObject root = sendRequest(request); Assert.assertNotNull("root is null.", root); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (UnsupportedEncodingException e) { fail("Exception in StringBody." + e.getMessage()); } }
From source file:org.hyperic.hq.hqapi1.HQConnection.java
/** * Issue a POST against the API./*from www .ja v a 2s . c om*/ * * @param path * The web service endpoint * @param params * A Map of key value pairs that are added to the post data * @param file * The file to post * @param responseHandler * The {@link org.hyperic.hq.hqapi1.ResponseHandler} to handle this response. * @return The response object from the operation. This response will be of * the type given in the responseHandler argument. * @throws IOException * If a network error occurs during the request. */ public <T> T doPost(String path, Map<String, String> params, File file, ResponseHandler<T> responseHandler) throws IOException { HttpPost post = new HttpPost(); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart(file.getName(), new FileBody(file)); for (Map.Entry<String, String> paramEntry : params.entrySet()) { multipartEntity.addPart(new FormBodyPart(paramEntry.getKey(), new StringBody(paramEntry.getValue()))); } post.setEntity(multipartEntity); return runMethod(post, path, responseHandler); }
From source file:org.andrico.andrico.facebook.FBBase.java
private MultipartEntity makeMultipartEntityFromParameters(FBMethod method, ByteArrayBody.WriteToProgressHandler runnable) throws UnsupportedEncodingException { MultipartEntity multipartEntity = new MultipartEntity(); for (String key : method.mParameters.keySet()) { multipartEntity.addPart(key, new StringBody(method.mParameters.get(key))); }//from www .ja v a 2 s . com multipartEntity.addPart("data", new ByteArrayBody(method.mData, method.mDataFilename, runnable)); return multipartEntity; }