List of usage examples for org.apache.http.entity.mime.content StringBody StringBody
public StringBody(final String text, final String mimeType, Charset charset) throws UnsupportedEncodingException
From source file:au.com.infiniterecursion.vidiom.utils.PublishingUtils.java
public Thread videoUploadToVideoBin(final Activity activity, final Handler handler, final String video_absolutepath, final String title, final String description, final String emailAddress, final long sdrecord_id) { Log.d(TAG, "doPOSTtoVideoBin starting"); // Make the progress bar view visible. ((VidiomActivity) activity).startedUploading(PublishingUtils.TYPE_VB); final Resources res = activity.getResources(); Thread t = new Thread(new Runnable() { public void run() { // Do background task. boolean failed = false; HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); URI url = null;/* w w w.j av a 2s . c o m*/ try { url = new URI(res.getString(R.string.http_videobin_org_add)); } catch (URISyntaxException e) { // Ours is a fixed URL, so not likely to get here. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); e.printStackTrace(); return; } HttpPost post = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); File file = new File(video_absolutepath); entity.addPart(res.getString(R.string.video_bin_API_videofile), new FileBody(file)); try { entity.addPart(res.getString(R.string.video_bin_API_api), new StringBody("1", "text/plain", Charset.forName("UTF-8"))); // title entity.addPart(res.getString(R.string.video_bin_API_title), new StringBody(title, "text/plain", Charset.forName("UTF-8"))); // description entity.addPart(res.getString(R.string.video_bin_API_description), new StringBody(description, "text/plain", Charset.forName("UTF-8"))); } catch (IllegalCharsetNameException e) { // error e.printStackTrace(); failed = true; } catch (UnsupportedCharsetException e) { // error e.printStackTrace(); return; } catch (UnsupportedEncodingException e) { // error e.printStackTrace(); failed = true; } post.setEntity(entity); // Here we go! String response = null; try { response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); } catch (ParseException e) { // error e.printStackTrace(); failed = true; } catch (ClientProtocolException e) { // error e.printStackTrace(); failed = true; } catch (IOException e) { // error e.printStackTrace(); failed = true; } client.getConnectionManager().shutdown(); // CHECK RESPONSE FOR SUCCESS!! if (!failed && response != null && response.matches(res.getString(R.string.video_bin_API_good_re))) { // We got back HTTP response with valid URL Log.d(TAG, " video bin got back URL " + response); } else { Log.d(TAG, " video bin got eror back:\n" + response); failed = true; } if (failed) { // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(false); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_failed_)); } }, 0); return; } // XXX Convert to preference for auto-email on videobin post // XXX ADD EMAIL NOTIF to all other upload methods // stuck on YES here, if email is defined. if (emailAddress != null && response != null) { // EmailSender through IR controlled gmail system. SSLEmailSender sender = new SSLEmailSender( activity.getString(R.string.automatic_email_username), activity.getString(R.string.automatic_email_password)); // consider // this // public // knowledge. try { sender.sendMail(activity.getString(R.string.vidiom_automatic_email), // subject.getText().toString(), activity.getString(R.string.url_of_hosted_video_is_) + " " + response, // body.getText().toString(), activity.getString(R.string.automatic_email_from), // from.getText().toString(), emailAddress // to.getText().toString() ); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } } // Log record of this URL in POSTs table dbutils.creatHostDetailRecordwithNewVideoUploaded(sdrecord_id, res.getString(R.string.http_videobin_org_add), response, ""); mainapp.removeSDFileRecordIDfromUploadingTrack(sdrecord_id, TYPE_VB); // Use the handler to execute a Runnable on the // main thread in order to have access to the // UI elements. handler.postDelayed(new Runnable() { public void run() { // Update UI // Indicate back to calling activity the result! // update uploadInProgress state also. ((VidiomActivity) activity).finishedUploading(true); ((VidiomActivity) activity) .createNotification(res.getString(R.string.upload_to_videobin_org_succeeded_)); } }, 0); } }); t.start(); return t; }
From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java
/** * /*ww w. j av a 2 s. c o m*/ * @date 2013-1-7 ?11:08:54 * @param toFetchURL * @return */ public FetchResult request(FetchRequest req) throws Exception { FetchResult fetchResult = new FetchResult(); HttpUriRequest request = null; HttpEntity entity = null; String toFetchURL = req.getUrl(); boolean isPost = false; try { if (Http.Method.GET.equalsIgnoreCase(req.getHttpMethod())) request = new HttpGet(toFetchURL); else if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())) { request = new HttpPost(toFetchURL); isPost = true; } else if (Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) request = new HttpPut(toFetchURL); else if (Http.Method.HEAD.equalsIgnoreCase(req.getHttpMethod())) request = new HttpHead(toFetchURL); else if (Http.Method.OPTIONS.equalsIgnoreCase(req.getHttpMethod())) request = new HttpOptions(toFetchURL); else if (Http.Method.DELETE.equalsIgnoreCase(req.getHttpMethod())) request = new HttpDelete(toFetchURL); else throw new Exception("Unknown http method name"); //???,?? // TODO ?delay? synchronized (mutex) { //?? long now = (new Date()).getTime(); //?Host?? if (now - lastFetchTime < config.getPolitenessDelay()) Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime)); //????HOST??URL lastFetchTime = (new Date()).getTime(); } //GZIP???GZIP? request.addHeader("Accept-Encoding", "gzip"); for (Iterator<Entry<String, String>> it = headers.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); request.addHeader(entry.getKey(), entry.getValue()); } //? Header[] headers = request.getAllHeaders(); for (Header h : headers) { Map<String, List<String>> hs = req.getHeaders(); String key = h.getName(); List<String> val = hs.get(key); if (val == null) val = new ArrayList<String>(); val.add(h.getValue()); hs.put(key, val); } req.getCookies().putAll(this.cookies); fetchResult.setReq(req); HttpEntity reqEntity = null; if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod()) || Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) { if (!req.getFiles().isEmpty()) { reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (Iterator<Entry<String, List<File>>> it = req.getFiles().entrySet().iterator(); it .hasNext();) { Entry<String, List<File>> e = it.next(); String paramName = e.getKey(); for (File file : e.getValue()) { // For File parameters ((MultipartEntity) reqEntity).addPart(paramName, new FileBody(file)); } } for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it .hasNext();) { Entry<String, List<Object>> e = it.next(); String paramName = e.getKey(); for (Object paramValue : e.getValue()) { // For usual String parameters ((MultipartEntity) reqEntity).addPart(paramName, new StringBody( String.valueOf(paramValue), "text/plain", Charset.forName("UTF-8"))); } } } else { List<NameValuePair> params = new ArrayList<NameValuePair>(req.getParams().size()); for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it .hasNext();) { Entry<String, List<Object>> e = it.next(); String paramName = e.getKey(); for (Object paramValue : e.getValue()) { params.add(new BasicNameValuePair(paramName, String.valueOf(paramValue))); } } reqEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8); } if (isPost) ((HttpPost) request).setEntity(reqEntity); else ((HttpPut) request).setEntity(reqEntity); } //?? HttpResponse response = httpClient.execute(request); headers = response.getAllHeaders(); for (Header h : headers) { Map<String, List<String>> hs = fetchResult.getHeaders(); String key = h.getName(); List<String> val = hs.get(key); if (val == null) val = new ArrayList<String>(); val.add(h.getValue()); hs.put(key, val); } //URL fetchResult.setFetchedUrl(toFetchURL); String uri = request.getURI().toString(); if (!uri.equals(toFetchURL)) if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL)) fetchResult.setFetchedUrl(uri); entity = response.getEntity(); //??? int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_NOT_FOUND) { Header locationHeader = response.getFirstHeader("Location"); //301?302?URL?? if (locationHeader != null && (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) fetchResult.setMovedToUrl( URLCanonicalizer.getCanonicalURL(locationHeader.getValue(), toFetchURL)); } //???OKURLstatusCode?? //??? if (this.site.getSkipStatusCode() != null && this.site.getSkipStatusCode().trim().length() > 0) { String[] scs = this.site.getSkipStatusCode().split(","); for (String code : scs) { int c = CommonUtil.toInt(code); //????entity if (statusCode == c) { assemPage(fetchResult, entity); break; } } } fetchResult.setStatusCode(statusCode); return fetchResult; } //?? if (entity != null) { fetchResult.setStatusCode(statusCode); assemPage(fetchResult, entity); return fetchResult; } } catch (Throwable e) { fetchResult.setFetchedUrl(e.toString()); fetchResult.setStatusCode(Status.INTERNAL_SERVER_ERROR.ordinal()); return fetchResult; } finally { try { if (entity == null && request != null) request.abort(); } catch (Exception e) { throw e; } } fetchResult.setStatusCode(Status.UNSPECIFIED_ERROR.ordinal()); return fetchResult; }
From source file:com.att.api.rest.RESTClient.java
/** * Sends an http POST multipart request. * * @param jsonObj JSON Object to set as the start part * @param fnames file names for any files to add * @return api response//from ww w . ja va2 s . com * * @throws RESTException if request was unsuccessful */ public APIResponse httpPost(JSONObject jsonObj, String[] fnames) throws RESTException { HttpResponse response = null; try { HttpClient httpClient = createClient(); HttpPost httpPost = new HttpPost(url); this.setHeader("Content-Type", "multipart/form-data; type=\"application/json\"; " + "start=\"<startpart>\"; boundary=\"foo\""); addInternalHeaders(httpPost); final Charset encoding = Charset.forName("UTF-8"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding); StringBody sbody = new StringBody(jsonObj.toString(), "application/json", encoding); FormBodyPart stringBodyPart = new FormBodyPart("root-fields", sbody); stringBodyPart.addField("Content-ID", "<startpart>"); entity.addPart(stringBodyPart); for (int i = 0; i < fnames.length; ++i) { final String fname = fnames[i]; String type = URLConnection.guessContentTypeFromStream(new FileInputStream(fname)); if (type == null) { type = URLConnection.guessContentTypeFromName(fname); } if (type == null) { type = "application/octet-stream"; } FileBody fb = new FileBody(new File(fname), type, "UTF-8"); FormBodyPart fileBodyPart = new FormBodyPart(fb.getFilename(), fb); fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">"); fileBodyPart.addField("Content-Location", fb.getFilename()); entity.addPart(fileBodyPart); } httpPost.setEntity(entity); return buildResponse(httpClient.execute(httpPost)); } catch (Exception e) { throw new RESTException(e); } finally { if (response != null) { this.releaseConnection(response); } } }
From source file:org.jkan997.slingbeans.slingfs.FileSystemServer.java
private ContentBody generateTextBody(String key, Object value) throws Exception { String mimeType = MimeTypeHelper.TEXT; String valStr = value.toString(); if (value instanceof Date) { mimeType = "jcr-value/" + PropertyType.TYPENAME_DATE.toLowerCase(); valStr = ISO8601.format((Date) value); }//from w w w. ja v a 2s . c o m if (value instanceof Long) { mimeType = "jcr-value/" + PropertyType.TYPENAME_LONG.toLowerCase(); valStr = value.toString(); } if (value instanceof Double) { mimeType = "jcr-value/" + PropertyType.TYPENAME_DOUBLE.toLowerCase(); valStr = value.toString().replace(',', '.'); } if (value instanceof Boolean) { mimeType = "jcr-value/" + PropertyType.TYPENAME_BOOLEAN.toLowerCase(); valStr = value.toString().toLowerCase(); } if (key.endsWith("jcr:data")) { mimeType = "jcr-value/binary"; } StringBody res = new StringBody(valStr, mimeType, UTF_8); return res; }
From source file:de.geomobile.joined.api.service.JOWebService.java
/** * Send a text message to friend// ww w . j a v a 2 s .c o m * * @param userId * The users id. * * @param secureToken * The users secureToken. * @param friendsId * The friends id to send this message * @param msg * The text message * @return The HashMap String with id and time * @throws JOFriendFinderServerException * @throws JOFriendFinderUnexpectedException * @throws JOFriendFinderHTTPException */ public String sendMessage(String userId, String secureToken, String friendsId, String msg) throws JOFriendFinderServerException, JOFriendFinderUnexpectedException, JOFriendFinderHTTPException { try { HttpClient httpClient = getNewHttpClient(); HttpPost httpPost = new HttpPost( getJoinedServerUrl() + JOConfig.FF_MESSAGE + "/" + userId + "/" + friendsId); httpPost.addHeader(getAuthenticationHeader(userId, secureToken)); MultipartEntity entity = new MultipartEntity(); entity.addPart(JOConfig.TEXT, new StringBody(msg, JOConfig.TEXT_PLAIN, Charset.forName(JOConfig.UTF_8))); // entity.addPart(Config.ATTACHMENT, new StringBody(placeJson, Config.TEXT_PLAIN, Charset.forName(Config.UTF_8))); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) { throw new JOFriendFinderServerException(); } else if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new JOFriendFinderUnexpectedException( "HTTP Error Code " + httpResponse.getStatusLine().getStatusCode()); } else { return getJsonStringFromResponse(httpResponse); } } catch (UnsupportedEncodingException e) { throw new JOFriendFinderUnexpectedException(e); } catch (ClientProtocolException e) { throw new JOFriendFinderHTTPException(e); } catch (IOException e) { throw new JOFriendFinderHTTPException(e); } }
From source file:ti.modules.titanium.network.TiHTTPClient.java
public void addPostData(String name, String value) { if (value == null) { value = ""; }/*from w w w. ja v a 2s. c o m*/ try { if (needMultipart) { // JGH NOTE: this seems to be a bug in RoR where it would puke if you // send a content-type of text/plain for key/value pairs in form-data // so we send an empty string by default instead which will cause the // StringBody to not include the content-type header. this should be // harmless for all other cases parts.put(name, new StringBody(value, "", null)); } else { nvPairs.add(new BasicNameValuePair(name, value.toString())); } } catch (UnsupportedEncodingException e) { nvPairs.add(new BasicNameValuePair(name, value.toString())); } }
From source file:fm.audiobox.core.models.MediaFile.java
/** * Uploads media file to {@code AudioBox.fm Cloud} drive * /*w w w . ja v a2s. c o m*/ * @param async when {@code true} the upload request will be processed asynchronously * @param uploadHandler the {@link UploadHandler} used to upload file * @param customFields when {@code true} it will upload also {@code title artist album ...} fields * @return the {@link IConnectionMethod} instance used for this upload * @throws ServiceException if any connection error occurrs * @throws LoginException if any login error occurrs */ public IConnectionMethod upload(boolean async, UploadHandler uploadHandler, boolean customFields) throws ServiceException, LoginException, ForbiddenException { String path = IConnector.URI_SEPARATOR.concat(Actions.upload.toString()); MultipartEntity entity = new MultipartEntity(); String mime = MimeTypes.getMime(uploadHandler.getFile()); if (mime == null) { throw new ServiceException("mime type error: file is not supported by AudioBox.fm"); } entity.addPart("files[]", uploadHandler); if (customFields) { List<NameValuePair> fields = this.toQueryParameters(false); for (NameValuePair field : fields) { try { if (field.getValue() != null) { entity.addPart(field.getName(), new StringBody(field.getValue(), "text/plain", Charset.forName("UTF-8"))); } } catch (UnsupportedEncodingException e) { log.warn("Entity " + field.getName() + " cannot be added due to: " + e.getMessage()); } } } if (this.hash != null) { IConnectionMethod request = this.getConnector(IConfiguration.Connectors.NODE).head(this, path, null, null, null); request.addHeader(X_MD5_FILE_HEADER, this.hash); Response r = request.send(false); if (!r.isOK()) { throw new ServiceException(r.getStatus(), r.getBody()); } } IConnectionMethod request = this.getConnector(IConfiguration.Connectors.NODE).post(this, path, null, null); uploadHandler.setRequestMethod(request); request.send(async, entity); return request; }