List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder setBoundary
public MultipartEntityBuilder setBoundary(final String boundary)
From source file:com.smartsheet.api.internal.AbstractResources.java
/** * Create a resource using Smartsheet REST API. * * Exceptions:/*from w w w . j a va 2 s .c om*/ * IllegalArgumentException : if any argument is null, or path is empty string * InvalidRequestException : if there is any problem with the REST API request * AuthorizationException : if there is any problem with the REST API authorization(access token) * ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) * SmartsheetRestException : if there is any other REST API related error occurred during the operation * SmartsheetException : if there is any other error occurred during the operation * * @param <T> the generic type * @param path the relative path of the resource collections * @param objectClass the resource object class * @param object the object to create * @return the created resource * @throws SmartsheetException the smartsheet exception */ protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName, InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException { Util.throwIfNull(path, object); Util.throwIfEmpty(path); HttpRequest request; final String boundary = "----" + System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path)); try { uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); } catch (Exception e) { throw new RuntimeException(e); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary); builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object), ContentType.APPLICATION_JSON); builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName); org.apache.http.HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); T obj = null; //implement switch case try { CloseableHttpResponse response = httpClient.execute(uploadFile); org.apache.http.HttpEntity responseEntity = response.getEntity(); obj = this.getSmartsheet().getJsonSerializer() .deserializeResult(objectClass, responseEntity.getContent()).getResult(); } catch (Exception e) { throw new RuntimeException(e); } return obj; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public void postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String boundary = null;//from www. ja v a 2 s. c o m StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; // Log.d("Debug", "JSONParser - command: " + command); if ("start".equals(command) || "startSelected".equals(command)) { url = url + "gui/?action=start&hash=" + hash; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = url + "gui/?action=pause&hash=" + hash; } if ("stop".equals(command) || "stopSelected".equals(command)) { url = url + "gui/?action=stop&hash=" + hash; Log.d("Debug", "Stoping torrent " + hash); } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("addTorrent".equals(command)) { URI hash_uri = null; try { hash_uri = new URI(hash); hash = hash_uri.toString(); // Log.d("Debug","Torrent URL: "+ hash); } catch (URISyntaxException e) { Log.e("Debug", "URISyntaxException: " + e.toString()); } url = url + "gui/?action=add-url&s=" + hash; // key = "urls"; } if ("addTorrentFile".equals(command)) { url = url + "gui/?action=add-file"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; // urlContentType = "multipart/form-data"; } // if ("pauseall".equals(command)) { // url = "command/pauseall"; // } // // if ("pauseAll".equals(command)) { // url = "command/pauseAll"; // } // // // if ("resumeall".equals(command)) { // url = "command/resumeall"; // } // // if ("resumeAll".equals(command)) { // url = "command/resumeAll"; // } if ("increasePrio".equals(command)) { url = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("decreasePrio".equals(command)) { url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("maxPrio".equals(command)) { url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("minPrio".equals(command)) { url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("recheckSelected".equals(command)) { url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash="); } // if ("toggleFirstLastPiecePrio".equals(command)) { // url = "command/toggleFirstLastPiecePrio"; // key = "hashes"; // // } // // if ("toggleSequentialDownload".equals(command)) { // url = "command/toggleSequentialDownload"; // key = "hashes"; // // } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } 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. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url + "&token=" + token; // Log.d("Debug", "JSONParser - url: " + url); HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } // In order to pass the has we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // Set content type and urls if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { // Log.d("Debug", "JSONParser - urlContentType: " + urlContentType); // Log.d("Debug", "JSONParser - hash: " + Uri.decode(URLEncoder.encode(hash, "UTF-8"))); // Log.d("Debug", "JSONParser - hash: " + hash); httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("torrent_file", file, ContentType.DEFAULT_BINARY, null); // builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); // e.printStackTrace(); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String limit = ""; String tracker = ""; String boundary = null;/*from ww w . j av a 2 s .c o m*/ String fileId = ""; String filePriority = ""; String result = ""; StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; String label = ""; if ("start".equals(command) || "startSelected".equals(command)) { url = "command/resume"; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = "command/pause"; } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = "command/delete"; key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = "command/deletePerm"; key = "hashes"; } if ("addTorrent".equals(command)) { url = "command/download"; key = "urls"; } if ("addTracker".equals(command)) { url = "command/addTrackers"; key = "hash"; } if ("addTorrentFile".equals(command)) { url = "command/upload"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; } if ("pauseall".equals(command)) { url = "command/pauseall"; } if ("pauseAll".equals(command)) { url = "command/pauseAll"; } if ("resumeall".equals(command)) { url = "command/resumeall"; } if ("resumeAll".equals(command)) { url = "command/resumeAll"; } if ("increasePrio".equals(command)) { url = "command/increasePrio"; key = "hashes"; } if ("decreasePrio".equals(command)) { url = "command/decreasePrio"; key = "hashes"; } if ("maxPrio".equals(command)) { url = "command/topPrio"; key = "hashes"; } if ("minPrio".equals(command)) { url = "command/bottomPrio"; key = "hashes"; } if ("setFilePrio".equals(command)) { url = "command/setFilePrio"; String[] tmpString = hash.split("&"); hash = tmpString[0]; fileId = tmpString[1]; filePriority = tmpString[2]; // Log.d("Debug", "hash: " + hash); // Log.d("Debug", "fileId: " + fileId); // Log.d("Debug", "filePriority: " + filePriority); } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("setUploadRateLimit".equals(command)) { url = "command/setTorrentsUpLimit"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } } if ("setDownloadRateLimit".equals(command)) { url = "command/setTorrentsDlLimit"; key = "hashes"; Log.d("Debug", "Hash before: " + hash); String[] tmpString = hash.split("&"); hash = tmpString[0]; try { limit = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { limit = "-1"; } // Log.d("Debug", "url: " + url); // Log.d("Debug", "Hashes: " + hash + " | limit: " + limit); } if ("recheckSelected".equals(command)) { url = "command/recheck"; } if ("toggleFirstLastPiecePrio".equals(command)) { url = "command/toggleFirstLastPiecePrio"; key = "hashes"; } if ("toggleSequentialDownload".equals(command)) { url = "command/toggleSequentialDownload"; key = "hashes"; } if ("toggleAlternativeSpeedLimits".equals(command)) { // Log.d("Debug", "Toggling alternative rates"); url = "command/toggleAlternativeSpeedLimits"; key = "hashes"; } if ("setLabel".equals(command)) { url = "command/setLabel"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("setCategory".equals(command)) { url = "command/setCategory"; key = "hashes"; String[] tmpString = hash.split("&"); hash = tmpString[0]; try { label = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { label = ""; } // Log.d("Debug", "Hash2: " + hash + "| label2: " + label); } if ("alternativeSpeedLimitsEnabled".equals(command)) { // Log.d("Debug", "Getting alternativeSpeedLimitsEnabled"); url = "command/alternativeSpeedLimitsEnabled"; key = "hashes"; } // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; } 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. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } if ("addTracker".equals(command)) { String[] tmpString = hash.split("&"); hash = tmpString[0]; URI hash_uri = new URI(hash); hash = hash_uri.toString(); try { tracker = tmpString[1]; } catch (ArrayIndexOutOfBoundsException e) { tracker = ""; } // Log.d("Debug", "addTracker - hash: " + hash); // Log.d("Debug", "addTracker - tracker: " + tracker); } // In order to pass the hash we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); // Add limit if (!limit.equals("")) { Log.d("Debug", "JSONParser - Limit: " + limit); nvps.add(new BasicNameValuePair("limit", limit)); } // Set values for setting file priority if ("setFilePrio".equals(command)) { nvps.add(new BasicNameValuePair("id", fileId)); nvps.add(new BasicNameValuePair("priority", filePriority)); } // Add label if (label != null && !label.equals("")) { label = Uri.decode(label); if ("setLabel".equals(command)) { nvps.add(new BasicNameValuePair("label", label)); } else { nvps.add(new BasicNameValuePair("category", label)); } // Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<"); } // Add tracker if (tracker != null && !tracker.equals("")) { nvps.add(new BasicNameValuePair("urls", tracker)); // Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<"); } String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8); // This replaces encoded char "+" for "%20" so spaces can be passed as parameter entityValue = entityValue.replaceAll("\\+", "%20"); StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8); stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE); httpget.setEntity(stringEntity); // Set content type and urls if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".equals(command) || "setFilePrio".equals(command) || "toggleAlternativeSpeedLimits".equals(command) || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command) || "setCategory".equals(command) || "addTracker".equals(command)) { httpget.setHeader("Content-Type", urlContentType); } // Set cookie if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } // Set content type and urls if ("addTorrentFile".equals(command)) { httpget.setHeader("Content-Type", urlContentType); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // Add boundary builder.setBoundary(boundary); // Add torrent file as binary File file = new File(hash); // FileBody fileBody = new FileBody(file); // builder.addPart("file", fileBody); builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash); // Build entity HttpEntity entity = builder.build(); // Set entity to http post httpget.setEntity(entity); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); // Log.d("Debug", "JSONPArser - command result: " + result); return result; } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (SSLPeerUnverifiedException e) { Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString()); throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("Debug", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return null; }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
@Override public final <RS> Will<Response<RS>> post(String resource, MultiPartRequest request, Class<RS> clazz) throws RestEndpointIOException { HttpPost post = new HttpPost(spliceUrl(resource)); try {//from w w w .j a v a2s .com MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (MultiPartRequest.MultiPartSerialized<?> serializedPart : request.getSerializedRQs()) { Serializer serializer = getSupportedSerializer(serializedPart); builder.addPart(serializedPart.getPartName(), new StringBody(new String(serializer.serialize(serializedPart.getRequest())), ContentType.parse(serializer.getMimeType()))); } for (MultiPartRequest.MultiPartBinary partBinaty : request.getBinaryRQs()) { builder.addPart(partBinaty.getPartName(), new ByteArrayBody(partBinaty.getData().read(), ContentType.parse(partBinaty.getContentType()), partBinaty.getFilename())); } /* Here is some dirty hack to avoid problem with MultipartEntity and asynchronous http client * Details can be found here: http://comments.gmane.org/gmane.comp.apache.httpclient.user/2426 * * The main idea is to replace MultipartEntity with NByteArrayEntity once first * doesn't support #getContent method * which is required for async client implementation. So, we are copying response * body as byte array to NByteArrayEntity to * leave it unmodified. * * Alse we need to add boundary value to content type header. Details are here: * http://en.wikipedia.org/wiki/Delimiter#Content_boundary * MultipartEntity generates correct header by yourself, but we need to put it * manually once we replaced entity type to NByteArrayEntity */ String boundary = "-------------" + UUID.randomUUID().toString(); builder.setBoundary(boundary); ByteArrayOutputStream baos = new ByteArrayOutputStream(); builder.build().writeTo(baos); post.setEntity(new NByteArrayEntity(baos.toByteArray(), ContentType.MULTIPART_FORM_DATA)); post.setHeader("Content-Type", "multipart/form-data;boundary=" + boundary); } catch (Exception e) { throw new RestEndpointIOException("Unable to build post multipart request", e); } return executeInternal(post, new ClassConverterCallback<RS>(serializers, clazz)); }
From source file:org.kohsuke.stapler.RequestImplTest.java
private byte[] generateMultipartData() throws IOException { MultipartEntityBuilder reqEntityBuilder = MultipartEntityBuilder.create(); reqEntityBuilder.setBoundary("mpboundary"); reqEntityBuilder.addBinaryBody("pomFile", new File("./pom.xml"), ContentType.TEXT_XML, "pom.xml"); reqEntityBuilder.addTextBody("text1", "text1_val"); reqEntityBuilder.addTextBody("text2", "text2_val"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {/*from w w w . jav a2 s. com*/ reqEntityBuilder.build().writeTo(outputStream); outputStream.flush(); return outputStream.toByteArray(); } finally { outputStream.close(); } }