List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
From source file:illab.nabal.proxy.AbstractContext.java
/** * Add multipart data to given HTTP POST object. * /*from w w w .ja va 2 s . co m*/ * @param httpPost * @param params * @param paramNameForFile * @param file * @return HttpPost * @throws Exception */ protected synchronized HttpPost getMultipartHttpPost(HttpPost httpPost, List<NameValuePair> params, String paramNameForFile, File file) throws Exception { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (params != null && params.size() > 0) { for (NameValuePair nvPair : params) { entity.addPart(nvPair.getName(), new StringBody(StringHelper.nvl(nvPair.getValue()))); } } // check if given File is an actual file if (file == null || file.isFile() == false) { throw new Exception("File is invalid. check file path."); } else { entity.addPart(paramNameForFile, new FileBody(file)); } httpPost.setEntity(entity); return httpPost; }
From source file:nl.esciencecenter.ptk.web.WebClient.java
/** * Perform a managed Http Put with a String as Attachment. *//*from ww w .ja v a 2s . co m*/ public int doPutString(String query, String text, StringHolder resultTextH, boolean inbody) throws WebException { HttpPut putMethod = null; URI uri = resolve(query); StringHolder contentTypeH = new StringHolder(); putMethod = new HttpPut(uri.toString()); MultipartEntity multiPart = new MultipartEntity(); StringBody stringB; try { stringB = new StringBody(text); multiPart.addPart("caption", stringB); } catch (UnsupportedEncodingException e) { new WebException(WebException.Reason.IOEXCEPTION, "Unsupported Encoding Exception:" + e.getMessage(), e); } putMethod.setEntity(multiPart); // Method int status = executePut(putMethod, resultTextH, contentTypeH); // Status return this.checkHttpStatus(status, "doPutString():" + query, resultTextH, contentTypeH); }
From source file:org.botlibre.sdk.SDKConnection.java
public String POSTFILE(String url, String path, String name, String xml) { if (this.debug) { System.out.println("POST: " + url); System.out.println("file: " + path); System.out.println("XML: " + xml); }//w ww . j a va2 s . c om String result = ""; try { File file = new File(path); FileInputStream stream = new FileInputStream(file); ByteArrayOutputStream output = new ByteArrayOutputStream(); int read = 0; byte[] buffer = new byte[4096]; while ((read = stream.read(buffer)) != -1) { output.write(buffer, 0, read); } byte[] byte_arr = output.toByteArray(); stream.close(); ByteArrayBody fileBody = new ByteArrayBody(byte_arr, name); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("file", fileBody); multipartEntity.addPart("xml", new StringBody(xml)); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; HttpPost httppost = new HttpPost(url); httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, HTTP.UTF_8); } if ((response.getStatusLine().getStatusCode() != 200) && (response.getStatusLine().getStatusCode() != 204)) { this.exception = new SDKException("" + response.getStatusLine().getStatusCode() + " : " + result); throw this.exception; } } catch (Exception exception) { this.exception = new SDKException(exception); throw this.exception; } return result; }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
private MultipartEntity getMultipartEntity(API api, String externalPublisher, String action) throws org.wso2.carbon.registry.api.RegistryException, IOException, UserStoreException, APIManagementException {/*from w w w. j ava2 s.c o m*/ MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { entity.addPart(APIConstants.API_ACTION, new StringBody(action)); entity.addPart("name", new StringBody(api.getId().getApiName())); entity.addPart("version", new StringBody(api.getId().getVersion())); entity.addPart("provider", new StringBody(externalPublisher)); entity.addPart("description", new StringBody(checkValue(api.getDescription()))); entity.addPart("endpoint", new StringBody(checkValue(api.getUrl()))); entity.addPart("sandbox", new StringBody(checkValue(api.getSandboxUrl()))); entity.addPart("wsdl", new StringBody(checkValue(api.getWsdlUrl()))); entity.addPart("wadl", new StringBody(checkValue(api.getWadlUrl()))); entity.addPart("endpoint_config", new StringBody(checkValue(api.getEndpointConfig()))); String registryIconUrl = getFullRegistryIconUrl(api.getThumbnailUrl()); URL url = new URL(getIconUrlWithHttpRedirect(registryIconUrl)); File fileToUpload = new File("tmp/icon"); if (!fileToUpload.exists()) { if (!fileToUpload.createNewFile()) { String message = "Unable to create a new temp file"; log.error(message); throw new APIManagementException(message); } } FileUtils.copyURLToFile(url, fileToUpload); FileBody fileBody = new FileBody(fileToUpload, "application/octet-stream"); entity.addPart("apiThumb", fileBody); // fileToUpload.delete(); StringBuilder tagsSet = new StringBuilder(); Iterator it = api.getTags().iterator(); int j = 0; while (it.hasNext()) { Object tagObject = it.next(); tagsSet.append((String) tagObject); if (j != api.getTags().size() - 1) { tagsSet.append(','); } j++; } entity.addPart("tags", new StringBody(checkValue(tagsSet.toString()))); StringBuilder tiersSet = new StringBuilder(); Iterator tier = api.getAvailableTiers().iterator(); int k = 0; while (tier.hasNext()) { Object tierObject = tier.next(); Tier availTier = (Tier) tierObject; tiersSet.append(availTier.getName()); if (k != api.getAvailableTiers().size() - 1) { tiersSet.append(','); } k++; } entity.addPart("tiersCollection", new StringBody(checkValue(tiersSet.toString()))); entity.addPart("context", new StringBody(api.getContext())); entity.addPart("bizOwner", new StringBody(checkValue(api.getBusinessOwner()))); entity.addPart("bizOwnerMail", new StringBody(checkValue(api.getBusinessOwnerEmail()))); entity.addPart("techOwnerMail", new StringBody(checkValue(api.getTechnicalOwnerEmail()))); entity.addPart("techOwner", new StringBody(checkValue(api.getTechnicalOwner()))); entity.addPart("visibility", new StringBody(api.getVisibility())); entity.addPart("roles", new StringBody(checkValue(api.getVisibleRoles()))); entity.addPart("endpointType", new StringBody(checkValue(String.valueOf(api.isEndpointSecured())))); entity.addPart("endpointAuthType", new StringBody(checkValue(String.valueOf(api.isEndpointAuthDigest())))); entity.addPart("epUsername", new StringBody(checkValue(api.getEndpointUTUsername()))); entity.addPart("epPassword", new StringBody(checkValue(api.getEndpointUTPassword()))); entity.addPart("apiOwner", new StringBody(api.getId().getProviderName())); entity.addPart("advertiseOnly", new StringBody("true")); String tenantDomain = MultitenantUtils .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName())); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager() .getTenantId(tenantDomain); entity.addPart("redirectURL", new StringBody(getExternalStoreRedirectURL(tenantId))); if (api.getTransports() == null) { entity.addPart("http_checked", new StringBody("")); entity.addPart("https_checked", new StringBody("")); } else { String[] transports = api.getTransports().split(","); if (transports.length == 1) { if ("https".equals(transports[0])) { entity.addPart("http_checked", new StringBody("")); entity.addPart("https_checked", new StringBody(transports[0])); } else { entity.addPart("https_checked", new StringBody("")); entity.addPart("http_checked", new StringBody(transports[0])); } } else { entity.addPart("http_checked", new StringBody("http")); entity.addPart("https_checked", new StringBody("https")); } } entity.addPart("resourceCount", new StringBody(String.valueOf(api.getUriTemplates().size()))); Iterator urlTemplate = api.getUriTemplates().iterator(); int i = 0; while (urlTemplate.hasNext()) { Object templateObject = urlTemplate.next(); URITemplate template = (URITemplate) templateObject; entity.addPart("uriTemplate-" + i, new StringBody(template.getUriTemplate())); entity.addPart("resourceMethod-" + i, new StringBody(template.getMethodsAsString().replaceAll("\\s", ","))); entity.addPart("resourceMethodAuthType-" + i, new StringBody(String.valueOf(template.getAuthTypeAsString().replaceAll("\\s", ",")))); entity.addPart("resourceMethodThrottlingTier-" + i, new StringBody(template.getThrottlingTiersAsString().replaceAll("\\s", ","))); i++; } return entity; } catch (UnsupportedEncodingException e) { throw new IOException("Error while adding the API to external APIStore :", e); } }
From source file:com.stikyhive.stikyhive.ChattingActivity.java
public int uploadFile(final File SDFile) { String status = ""; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(upLoadServerUri); FileBody bin = new FileBody(SDFile); MultipartEntity reqEntity = new MultipartEntity(); try {// www . j a v a 2s .c o m reqEntity.addPart("Content-Disposition", new StringBody("multipart/form-data")); // reqEntity.addPart("filename", new StringBody(filename)); reqEntity.addPart("uploaded_file", bin); reqEntity.addPart("Content-Type", new StringBody("image/png")); httppost.setEntity(reqEntity); //Log.d("Executing Request ", httppost.getRequestLine().toString()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); this.runOnUiThread(new Runnable() { @Override public void run() { //dialog.show(); } }); if (resEntity != null) { Log.i("content length: ", resEntity.getContentLength() + ""); if (resEntity.getContentLength() > 0) { fileNameRes = EntityUtils.toString(resEntity); Log.i(TAG, " Status ... ^^ " + status); return 200; } else { status = "No Response from Server"; Log.i("Status----->", status); return 500; } } else { status = "No Response from Server"; Log.i("Status----->", status); return 500; } } catch (Exception e) { e.printStackTrace(); status = "Unable to connect with server"; return 500; } }
From source file:org.deviceconnect.android.profile.restful.test.FailFileDescriptorProfileTestCase.java
/** * ?????????./*from w ww . j a va2 s . com*/ * <pre> * ?HTTP * Method: PUT * Path: /file_descriptor/write?deviceId=xxxxx&mediaId=xxxx&abc=abc * Multipart: media * </pre> * <pre> * ?? * ??????? * result?0??????? * </pre> */ public void testPutWriteUndefinedAttribute() { URIBuilder builder = TestURIBuilder.createURIBuilder(); builder.setProfile(FileDescriptorProfileConstants.PROFILE_NAME); builder.setAttribute(FileDescriptorProfileConstants.ATTRIBUTE_WRITE); builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()); builder.addParameter(FileDescriptorProfileConstants.PARAM_PATH, TestFileDescriptorProfileConstants.PATH); builder.addParameter("abc", "abc"); builder.addParameter(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); assertResultOK(root); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } catch (UnsupportedEncodingException e) { fail("Exception in StringBody." + e.getMessage()); } }
From source file:sjizl.com.ChatActivity.java
private void doFileUpload(String path) { String username = ""; String password = ""; String foto = ""; String foto_num = ""; SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE); username = sp.getString("username", null); password = sp.getString("password", null); foto = sp.getString("foto", null); foto_num = sp.getString("foto_num", null); File file1 = new File(path); String urlString = "http://sjizl.com/postBD/UploadToServer.php?intochat=1&pid_user=" + pid_user + "&username=" + username + "&password=" + password; try {//from ww w . j a v a 2 s .c om HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); FileBody bin1 = new FileBody(file1); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("uploadedfile1", bin1); reqEntity.addPart("user", new StringBody("User")); post.setEntity(reqEntity); HttpResponse response = client.execute(post); resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE", response_str); runOnUiThread(new Runnable() { public void run() { try { // res.setTextColor(Color.GREEN); // res.setText("n Response from server : n " + response_str); CommonUtilities.custom_toast(getApplicationContext(), ChatActivity.this, "Upload Complete! ", null, R.drawable.iconbd); new UpdateChat().execute(); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } //RegisterActivity.login(username,password,getApplicationContext()); CommonUtilities.startandsendwebsock( "" + pid_user + " " + pid + " " + naam + " " + foto + " " + foto_num + " message send"); }
From source file:net.kidlogger.kidlogger.KLService.java
protected void sendPOST(File f, String content, String mimeType, boolean delFile, boolean increaseUploadedSize) { Date now = new Date(); String fileDate = String.format("%td/%tm/%tY %tT", now, now, now, now); String devField = Settings.getDeviceField(this); if (devField.equals("undefined") || devField.equals("")) { return;//from w w w . java 2 s . com } if (f == null) { //app.logError(CN + "sendPOST", "f parameter is null"); return; } if (mimeType == null) { //app.logError(CN + "sendPOST", "mime parameter is null"); return; } try { //HttpParams params = new BasicHttpParams(); //HttpConnectionParams.setSoTimeout(params, 40000); //HttpConnectionParams.setConnectionTimeout(params, 40000); //HttpClient client = new DefaultHttpClient(params); HttpClient client = new DefaultHttpClient(); String postUrl = getString(R.string.upload_link); //String postUrl = "http://10.0.2.2/denwer/"; HttpPost post = new HttpPost(postUrl); FileBody bin = new FileBody(f, mimeType, f.getName()); StringBody sb1 = new StringBody(devField); //dYZ-PC-Gzq StringBody sb2 = new StringBody(content); StringBody sb3 = new StringBody("Android " + Build.VERSION.RELEASE); StringBody sb4 = new StringBody(Settings.getApiVersion(this)); StringBody sb5 = new StringBody(fileDate); StringBody sb6 = new StringBody("append"); MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT); reqEntity.addPart("file", bin); reqEntity.addPart("device", sb1); reqEntity.addPart("content", sb2); reqEntity.addPart("client-ver", sb3); reqEntity.addPart("app-ver", sb4); reqEntity.addPart("client-date-time", sb5); reqEntity.addPart("file-store", sb6); post.setEntity(reqEntity); // Check Internet connection //if(isInternetOn()){ if (!mNoConnectivity) { HttpResponse response = client.execute(post); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { pStatus = EntityUtils.toString(resEntity); if (pStatus.equalsIgnoreCase("Ok")) { if (mimeType.equals("text/html")) saveToPref("filePointer", filePointer); FILE_SENT = f.getName(); SIZE_SENT = f.length(); postSentOk = true; app.mSendTime = new String(fileDate); if (increaseUploadedSize) uploadedSize = uploadedSize + (int) f.length(); } else { // Check response of server if (pStatus.contains("<html>")) return; else if (pStatus.contains(new String(REJECT))) stopUploadMedia = true; else if (pStatus.contains(new String(UPDATE)) || pStatus.contains(new String(BAD_DEV)) || pStatus.contains(new String(NOT_FOUND))) unregisterReceiver(timeTick); //app.logError(CN + "sendPOST", pStatus + " file: " + f.getName()); } app.logError(CN + "sendPOST", "Response: " + pStatus + " file: " + f.getName() + " size: " + f.length()); //Log.i(CN + "sendPOST", "Response: " + pStatus); } else app.logError(CN + "sendPOST", "Response is NULL"); } //else // app.logError(CN + "sendPOST", "No any Internet connections"); if (delFile) { f.delete(); } } catch (Exception e) { if (delFile) { f.delete(); } app.logError(CN + "sendPOST", e.toString() + " file:" + f.getName() + " size: " + f.length()); } }