List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text) throws UnsupportedEncodingException
From source file:org.jutge.joc.porra.service.EmailService.java
/** * Mighty delicate a process it is to send an email through the Raco webmail frontend. Let me break it down: * You need to log in as you'd normally do in the Raco. After a couple of redirects to the CAS server, you should be inside. * Then you issue a GET for the mail compose form. The response contains a form token to be used in the actual multipart POST that should send the mail. * The minute they change the login system or the webmail styles, this'll probably break down LOL: Let's hope they keep it this way til the Joc d'EDA is over * @param userAccount user to send the mail to * @param message the message body//from w w w . j a v a 2 s . com * @throws Exception should anything crash */ private void sendMail(final Account userAccount, final String message) throws Exception { // Enviar mail pel Raco // Authenticate final List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("service", "https://raco.fib.upc.edu/oauth/gestio-api/api.jsp")); params.add(new BasicNameValuePair("loginDirecte", "true")); params.add(new BasicNameValuePair("username", "XXXXXXXX")); params.add(new BasicNameValuePair("password", "XXXXXXXX")); HttpPost post = new HttpPost("https://raco.fib.upc.edu/cas/login"); post.setEntity(new UrlEncodedFormEntity(params)); final DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { public boolean isRedirected(final HttpRequest request, final HttpResponse response, final HttpContext context) { boolean isRedirect = false; try { isRedirect = super.isRedirected(request, response, context); } catch (ProtocolException e) { EmailService.this.logger.error(e.getMessage()); } if (!isRedirect) { final int responseCode = response.getStatusLine().getStatusCode(); isRedirect = responseCode == 301 || responseCode == 302; } return isRedirect; } }); HttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); EntityUtils.consumeQuietly(entity); // get form page final HttpGet get = new HttpGet("https://webmail.fib.upc.es/horde/imp/compose.php?thismailbox=INBOX&uniq=" + System.currentTimeMillis()); response = httpClient.execute(get); entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); // Find form action with uniq parameter Pattern pattern = Pattern.compile(RacoUtils.RACO_MAIL_ACTION_PATTERN); Matcher matcher = pattern.matcher(responseBody); matcher.find(); final String action = matcher.group(); // formtoken responseBody = responseBody.substring(matcher.end(), responseBody.length()); pattern = Pattern.compile(RacoUtils.RACO_FORMTOKEN_PATTERN); matcher = pattern.matcher(responseBody); matcher.find(); String formToken = matcher.group(); formToken = formToken.substring(28, formToken.length()); // to final String email = userAccount.getEmail(); // Send mail - it's a multipart post final MultipartEntity multipart = new MultipartEntity(); multipart.addPart("MAX_FILE_SIZE", new StringBody("1038090240")); multipart.addPart("actionID", new StringBody("send_message")); multipart.addPart("__formToken_compose", new StringBody(formToken)); multipart.addPart("messageCache", new StringBody("")); multipart.addPart("spellcheck", new StringBody("")); multipart.addPart("page", new StringBody("")); multipart.addPart("start", new StringBody("")); multipart.addPart("thismailbox", new StringBody("INBOX")); multipart.addPart("attachmentAction", new StringBody("")); multipart.addPart("reloaded", new StringBody("1")); multipart.addPart("oldrtemode", new StringBody("")); multipart.addPart("rtemode", new StringBody("1")); multipart.addPart("last_identity", new StringBody("0")); multipart.addPart("from", new StringBody("porra-joc-eda@est.fib.upc.edu")); multipart.addPart("to", new StringBody(email)); multipart.addPart("cc", new StringBody("")); multipart.addPart("bcc", new StringBody("")); multipart.addPart("subject", new StringBody("Activacio Porra Joc EDA")); multipart.addPart("charset", new StringBody("UTF-8")); multipart.addPart("save_sent_mail", new StringBody("on")); multipart.addPart("message", new StringBody(message)); multipart.addPart("upload_1", new StringBody("")); multipart.addPart("upload_disposition_1", new StringBody("attachment")); multipart.addPart("save_attachments_select", new StringBody("0")); multipart.addPart("link_attachments", new StringBody("0")); post = new HttpPost("https://webmail.fib.upc.es/horde/imp/" + action); post.setEntity(multipart); response = httpClient.execute(post); EntityUtils.consumeQuietly(entity); this.logger.info("EmailService.sendMail done"); }
From source file:org.apache.sling.testing.tools.osgi.WebconsoleClient.java
/** Start specified bundle */ public void startBundle(String symbolicName) throws Exception { // To start the bundle we POST action=start to its URL final String path = getBundlePath(symbolicName, null); log.info("Starting bundle {} via {}", symbolicName, path); final MultipartEntity entity = new MultipartEntity(); entity.addPart("action", new StringBody("start")); executor.execute(builder.buildPostRequest(path).withCredentials(username, password).withEntity(entity)) .assertStatus(200);/*from w w w . j a v a2 s.com*/ }
From source file:org.opentraces.metatracker.net.OpenTracesClient.java
public void uploadFile(String fileName) { try {//from w w w .j av a 2 s. com DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(fileName); HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); Log.d(LOG_TAG, "Upload result: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (Throwable ex) { Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); } }
From source file:org.ubicompforall.BusTUC.Speech.HTTP.java
public DummyObj sendPost(String filePath, Context context, double lat, double lon) { String response = "Fant ikke noe"; long first = System.nanoTime(); Calc calc = new Calc(); DummyObj dummy = new DummyObj(); HttpClient httpclient = new DefaultHttpClient(); long second = System.nanoTime() - first; // File file = new File(Environment.getExternalStorageDirectory(), // filePath); File file = new File(filePath); HttpPost httppost = new HttpPost("http://vm-6114.idi.ntnu.no:1337/SpeechServer/sst"); final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String t_id = tm.getDeviceId(); String tmp = "TABuss"; String p_id = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID); try {/*w w w . j a va 2 s . co m*/ MultipartEntity entity = new MultipartEntity(); entity.addPart("lat", new StringBody(String.valueOf(lat))); entity.addPart("lon", new StringBody(String.valueOf(lon))); entity.addPart("devID", new StringBody(tmp + p_id)); entity.addPart("speechinput", new FileBody(file, "multipart/form-data;charset=\"UTF-8\"")); httppost.setEntity(entity); response = EntityUtils.toString(httpclient.execute(httppost).getEntity(), "UTF-8"); System.out.println("RESPONSE: " + response); dummy = calc.parse(response); } catch (ClientProtocolException e) { } catch (IOException e) { } return dummy; }
From source file:com.jelastic.JelasticService.java
public UploadResponse upload(AuthenticationResponse authenticationResponse) { UploadResponse uploadResponse = null; try {// w ww. j av a 2s. c o m DefaultHttpClient httpclient = getHttpClient(); final File file = new File(getDir() + File.separator + getFilename()); if (!file.exists()) { throw new IllegalArgumentException( "First build artifact and try again. Artifact not found in location: [" + file.getAbsolutePath() + "]"); } CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new CustomMultiPartEntity.ProgressListener() { public void transferred(long num) { if (((int) ((num / (float) totalSize) * 100)) != numSt) { System.out.println( "File Uploading : [" + (int) ((num / (float) totalSize) * 100) + "%]"); numSt = ((int) ((num / (float) totalSize) * 100)); } } }); multipartEntity.addPart("fid", new StringBody("123456")); multipartEntity.addPart("session", new StringBody(authenticationResponse.getSession())); multipartEntity.addPart("file", new FileBody(file)); totalSize = multipartEntity.getContentLength(); URI uri = URIUtils.createURI(getProtocol(), getApiHoster(), getPort(), getUrlUploader(), null, null); project.log("Upload url : " + uri.toString(), Project.MSG_DEBUG); HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(multipartEntity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpPost, responseHandler); project.log("Upload response : " + responseBody, Project.MSG_DEBUG); uploadResponse = deserialize(responseBody, UploadResponse.class); } catch (URISyntaxException | IOException e) { project.log(e.getMessage(), Project.MSG_ERR); } return uploadResponse; }
From source file:org.openbmap.soapclient.AsyncUploader.java
/** * Sends an authenticated http post request to upload file * @param file File to upload (full path) * @return true on response code 200, false otherwise *//*from w w w . j av a 2 s . c o m*/ private UploadResult httpPostRequest(final String file) { // TODO check network state // @see http://developer.android.com/training/basics/network-ops/connecting.html // Adjust HttpClient parameters final HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. // HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. //HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT); final DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); final HttpPost httppost = new HttpPost(mServer); try { final MultipartEntity entity = new MultipartEntity(); entity.addPart(FILE_FIELD, new FileBody(new File(file), "text/xml")); if ((mUser != null) && (mPassword != null)) { final String authorizationString = "Basic " + Base64.encodeToString((mUser + ":" + mPassword).getBytes(), Base64.NO_WRAP); httppost.setHeader("Authorization", authorizationString); } if (mToken != null) { entity.addPart(API_FIELD, new StringBody(mToken)); } httppost.setEntity(entity); final HttpResponse response = httpclient.execute(httppost); final int reply = response.getStatusLine().getStatusCode(); if (reply == 200) { // everything is ok if we receive HTTP 200 mSize = entity.getContentLength(); Log.i(TAG, "Uploaded " + file + ": Server reply " + reply); return UploadResult.OK; } else if (reply == 401) { Log.e(TAG, "Wrong username or password"); return UploadResult.WRONG_PASSWORD; } else { Log.w(TAG, "Error while uploading" + file + ": Server reply " + reply); return UploadResult.ERROR; } // TODO: redirects (301, 302) are NOT handled here // thus if something changes on the server side we're dead here } catch (final ClientProtocolException e) { Log.e(TAG, e.getMessage()); } catch (final IOException e) { Log.e(TAG, "I/O exception on file " + file); } return UploadResult.UNDEFINED; }
From source file:com.jaeksoft.searchlib.Monitor.java
private final void addIfNotNull(MultipartEntity reqEntity, String name, String value) throws UnsupportedEncodingException { if (value == null) return;// w w w.ja v a 2 s. co m reqEntity.addPart(name.replace('.', '_'), new StringBody(value)); }
From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java
private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken) throws URISyntaxException, UnsupportedEncodingException { String host = msgRequest.getTargetHost(); if (host == null) throw new URISyntaxException(host, "null URI"); if (!host.endsWith("/")) host += '/'; String address = msgRequest.getTargetAddress(); if (address == null) address = ""; if (address.startsWith("/")) address = address.substring(1);/* w w w . ja v a 2s .co m*/ String uriString = host + address; try { URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (MalformedURLException e) { throw new URISyntaxException(uriString, e.getMessage()); } if (msgRequest.getQuery() != null) uriString += "?" + msgRequest.getQuery(); // new URI(uriString); HttpRequestBase request = null; if (msgRequest.getMethod().equals(Method.POST)) { HttpPost post = new HttpPost(uriString); HttpEntity httpEntity = null; if (msgRequest.getRequestParams() != null) { // if body and requestparams are either not null there is an // exception if (msgRequest.getBody() != null && msgRequest != null) { throw new IllegalArgumentException("body and requestParams cannot be either populated"); } httpEntity = new MultipartEntity(); for (RequestParam param : msgRequest.getRequestParams()) { if (param.getParamName() == null || param.getParamName().trim().length() == 0) { throw new IllegalArgumentException("paramName cannot be null or empty"); } if (param instanceof FileRequestParam) { FileRequestParam fileparam = (FileRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody( fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename())); } if (param instanceof ObjectRequestParam) { ObjectRequestParam objectparam = (ObjectRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new StringBody(convertObject(objectparam.getVars()))); } } // mpe.addPart("file", // new ByteArrayBody(msgRequest.getFileContent(), "")); // post.setEntity(mpe); } if (msgRequest.getBody() != null) { httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET); ((StringEntity) httpEntity).setContentType(msgRequest.getContentType()); } post.setEntity(httpEntity); request = post; } else if (msgRequest.getMethod().equals(Method.PUT)) { HttpPut put = new HttpPut(uriString); if (msgRequest.getBody() != null) { StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET); se.setContentType(msgRequest.getContentType()); put.setEntity(se); } request = put; } else if (msgRequest.getMethod().equals(Method.DELETE)) { request = new HttpDelete(uriString); } else { // default: GET request = new HttpGet(uriString); } Map<String, String> headers = new HashMap<String, String>(); // default headers if (appToken != null) { headers.put(RequestHeader.APP_TOKEN.toString(), appToken); } if (authToken != null) { // is here for compatibility headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken); headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken); } headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType()); if (msgRequest.getCustomHeaders() != null) { headers.putAll(msgRequest.getCustomHeaders()); } for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } return request; }
From source file:com.ad.mediasharing.ADUploadMediaTask.java
@Override protected String doInBackground(Void... params) { String serverResponse = ""; try {// www .java2s . c om // Set timeout parameters int timeout = ADMediaSharingConstants.UPLOAD_REQUEST_TIME_OUT; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeout); HttpConnectionParams.setSoTimeout(httpParameters, timeout); // Initiate connection parts HttpClient client = new DefaultHttpClient(httpParameters); HttpPost postRequest = new HttpPost(mRequest.getRemoteRequestUri()); // Add headers if (!mRequest.getRequestHeaders().isEmpty()) { for (String sKey : mRequest.getRequestHeaders().keySet()) { String sValue = mRequest.getRequestHeaders().get(sKey); postRequest.addHeader(sKey, sValue); } } FileBody media = getMediaType(mRequest.getMediaFile()); postRequest.addHeader("Media-Type", media.getMimeType()); ADCustomMultiPartEntity multipartE = new ADCustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, new ADCustomMultiPartEntity.ProgressListener() { int lastPourcent = 0; @TargetApi(Build.VERSION_CODES.CUPCAKE) @Override public void transferred(long num) { int currentPourcent = (int) ((num / (float) totalSize) * 100); if (currentPourcent > lastPourcent && currentPourcent < 90) { publishProgress(currentPourcent); lastPourcent = currentPourcent; } } }); // Add the post elements multipartE.addPart("file", media); if (mRequest.getPostBodyParams() != null) { for (String sKey : mRequest.getPostBodyParams().keySet()) { String sVal = mRequest.getPostBodyParams().get(sKey); multipartE.addPart(sKey, new StringBody(sVal)); } } totalSize = multipartE.getContentLength(); postRequest.setEntity(multipartE); HttpResponse response = client.execute(postRequest); // Get the response from server HttpEntity theEnt = response.getEntity(); serverResponse = EntityUtils.toString(theEnt); if (ADMediaSharingConstants.DEBUG) { Log.d(TAG, "Result: " + serverResponse); } //Show the remaining progress. mProgressHandler.post(new Runnable() { public void run() { int i = uploadProgress; while (i <= 100) { try { publishProgress(i); i++; } catch (Exception e) { if (ADMediaSharingConstants.DEBUG) Log.d(TAG, e.getMessage()); } } } }); } catch (SocketTimeoutException e) { e.printStackTrace(); serverResponse = "unreachable"; } catch (ConnectTimeoutException e) { e.printStackTrace(); serverResponse = "unreachable"; } catch (Exception e) { e.printStackTrace(); serverResponse = "unreachable"; } return serverResponse; }
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from w ww .j a v a 2 s .c o m*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }