List of usage examples for org.apache.http.entity.mime.content FileBody FileBody
public FileBody(final File file)
From source file:com.careerly.utils.HttpClientUtils.java
/** * /*w ww . ja v a2s . c o m*/ * * @param url * @param key * @param files * @return */ public static String postFile(String url, String key, List<File> files) { HttpPost post = new HttpPost(url); String content = null; MultipartEntity multipartEntity = new MultipartEntity(); for (File file : files) { multipartEntity.addPart(key, new FileBody(file)); } try { post.setEntity(multipartEntity); HttpResponse response = HttpClientUtils.client.execute(post); content = EntityUtils.toString(response.getEntity()); } catch (Exception e) { HttpClientUtils.logger.error(String.format("post [%s] happens error ", url), e); } return content; }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static HttpUriRequest createUploadFileToServerRequest(String URL, String userName, final String fileName) { HttpPost request = new HttpPost(URL); String path = fileName;//from ww w . j a va2 s.c o m if (URL.indexOf("deletefile") == -1) {//$NON-NLS-1$ if (URL.indexOf("deployjob") != -1) {//$NON-NLS-1$ path = URL.substring(URL.indexOf("=") + 1);//$NON-NLS-1$ } MultipartEntity entity = new MultipartEntity(); entity.addPart(path, new FileBody(new File(fileName))); request.setEntity(entity); } addStudioToken(request, userName); return request; }
From source file:ecblast.test.EcblastTest.java
public String compareReactions(String queryFormat, String query, String targetFormat, String target) throws Exception { DefaultHttpClient client;// w w w .j av a 2 s . c om client = new DefaultHttpClient(); String urlString = "http://localhost:8080/ecblast-rest/compare"; HttpPost postRequest = new HttpPost(urlString); try { //Set various attributes MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")); //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())); switch (queryFormat) { case "RXN": FileBody fileBody = new FileBody(new File(query)); //Prepare payload multiPartEntity.addPart("q", fileBody); multiPartEntity.addPart("Q", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); break; case "SMI": multiPartEntity.addPart("q", new StringBody(query, "text/plain", Charset.forName("UTF-8"))); multiPartEntity.addPart("Q", new StringBody("SMI", "text/plain", Charset.forName("UTF-8"))); break; } switch (targetFormat) { case "RXN": FileBody fileBody = new FileBody(new File(target)); //Prepare payload multiPartEntity.addPart("t", fileBody); multiPartEntity.addPart("T", new StringBody("RXN", "text/plain", Charset.forName("UTF-8"))); break; case "SMI": multiPartEntity.addPart("t", new StringBody(target, "text/plain", Charset.forName("UTF-8"))); multiPartEntity.addPart("T", new StringBody("SMI", "text/plain", Charset.forName("UTF-8"))); break; } //Set to request body postRequest.setEntity(multiPartEntity); //Send request HttpResponse response = client.execute(postRequest); //Verify response if any if (response != null) { System.out.println(response.getStatusLine().getStatusCode()); return response.toString(); } } catch (IOException ex) { } return null; }
From source file:com.francisli.processing.http.HttpClient.java
/** * @param files HashMap: a collection of files to send to the server *//*from ww w . j av a2 s . c o m*/ public HttpRequest POST(String path, Map params, Map files) { //// clean up path a little bit- remove whitespace, add slash prefix path = path.trim(); if (!path.startsWith("/")) { path = "/" + path; } //// finally, invoke request HttpPost post = new HttpPost(getHost().toURI() + path); MultipartEntity multipart = null; //// if files passed, set up a multipart request if (files != null) { multipart = new MultipartEntity(); post.setEntity(multipart); for (Object key : files.keySet()) { Object value = files.get(key); if (value instanceof byte[]) { multipart.addPart((String) key, new ByteArrayBody((byte[]) value, "bytes.dat")); } else if (value instanceof String) { File file = new File((String) value); if (!file.exists()) { file = parent.sketchFile((String) value); } multipart.addPart((String) key, new FileBody(file)); } } } //// if params passed, format into a query string and append if (params != null) { if (multipart == null) { ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); for (Object key : params.keySet()) { Object value = params.get(key); pairs.add(new BasicNameValuePair(key.toString(), value.toString())); } String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8); if (path.contains("?")) { path = path + "&" + queryString; } else { path = path + "?" + queryString; } try { post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8)); } catch (UnsupportedEncodingException ex) { System.err.println("HttpClient: Unable to set POST data from parameters"); } } else { for (Object key : params.keySet()) { Object value = params.get(key); try { multipart.addPart((String) key, new StringBody((String) value)); } catch (UnsupportedEncodingException ex) { System.err.println("HttpClient: Unable to add " + key + ", " + value); } } } } if (useOAuth) { OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret); consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret); try { consumer.sign(post); } catch (Exception e) { System.err.println("HttpClient: Unable to sign POST request for OAuth"); } } HttpRequest request = new HttpRequest(this, getHost(), post); request.start(); return request; }
From source file:net.ymate.platform.module.wechat.support.HttpClientHelper.java
public String doUpload(String url, File uploadFile) throws Exception { CloseableHttpClient _httpClient = __doBuildHttpClient(); try {//from ww w .ja v a 2 s . c o m _LOG.debug("Upload File [" + uploadFile + "]"); String _result = EntityUtils .toString(_httpClient .execute(RequestBuilder.post().setUri(url) .setEntity(MultipartEntityBuilder.create() .addPart("media", new FileBody(uploadFile)).build()) .build()) .getEntity(), DEFAULT_CHARSET); _LOG.debug("Upload File [" + uploadFile + "] Response [" + _result + "]"); return _result; } finally { _httpClient.close(); } }
From source file:net.dahanne.gallery3.client.business.G3Client.java
private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs, String requestMethod, File file) throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException { HttpClient defaultHttpClient = new DefaultHttpClient(); HttpRequestBase httpMethod;//from w w w.j av a 2 s .co m //are we using rewritten urls ? if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) { appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php"); } logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl); if (POST.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1); StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8")); multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("file", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } else { ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else if (PUT.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else if (DELETE.equals(requestMethod)) { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); //this is to avoid the HTTP 414 (length too long) error //it should only happen when getting items, index.php/rest/items?urls= // } else if(appendToGalleryUrl.length()>2000) { // String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?")); // String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("=")); // String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1); // httpMethod = new HttpPost(galleryItemUrl + resource); // httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); // nameValuePairs.add(new BasicNameValuePair(variable, value)); // ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity( // nameValuePairs)); } else { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); } if (existingApiKey != null) { httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey); } //adding the userAgent to the request httpMethod.setHeader(USER_AGENT, userAgent); HttpResponse response = null; String[] patternsArray = new String[3]; patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z"; patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z"; patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z"; try { // be extremely careful here, android httpclient needs it to be // an // array of string, not an arraylist defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray); response = defaultHttpClient.execute(httpMethod); } catch (ClassCastException e) { List<String> patternsList = Arrays.asList(patternsArray); defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList); response = defaultHttpClient.execute(httpMethod); } int responseStatusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = null; if (response.getEntity() != null) { responseEntity = response.getEntity(); } switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_MOVED_TEMP: //the gallery is using rewritten urls, let's remember it and re hit the server this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new G3BadRequestException(); case HttpURLConnection.HTTP_FORBIDDEN: //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url if (appendToGalleryUrl.contains(INDEX_PHP_REST)) { this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; } throw new G3ForbiddenException(); case HttpURLConnection.HTTP_NOT_FOUND: throw new G3ItemNotFoundException(); default: throw new G3GalleryException("HTTP code " + responseStatusCode); } return responseEntity; }
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 w w w . j a va2 s.c o 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:org.hyperic.hq.hqapi1.HQConnection.java
/** * Issue a POST against the API./*from ww w . j ava2s. com*/ * * @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:net.dahanne.gallery.g2.java.client.business.G2Client.java
private MultipartEntity createMultiPartEntityForSendImageToGallery(int albumName, File imageFile, String imageName, String summary, String description) throws GalleryConnectionException { if (imageName == null) { imageName = imageFile.getName().substring(0, imageFile.getName().indexOf(".")); }/* w w w . j a v a 2 s.co m*/ MultipartEntity multiPartEntity; try { multiPartEntity = new MultipartEntity(); multiPartEntity.addPart("g2_controller", new StringBody("remote.GalleryRemote", UTF_8)); multiPartEntity.addPart("g2_form[cmd]", new StringBody("add-item", UTF_8)); multiPartEntity.addPart("g2_form[set_albumName]", new StringBody("" + albumName, UTF_8)); if (authToken != null) { multiPartEntity.addPart("g2_authToken", new StringBody(authToken, UTF_8)); } multiPartEntity.addPart("g2_form[caption]", new StringBody(imageName, UTF_8)); multiPartEntity.addPart("g2_form[extrafield.Summary]", new StringBody(summary, UTF_8)); multiPartEntity.addPart("g2_form[extrafield.Description]", new StringBody(description, UTF_8)); multiPartEntity.addPart("g2_userfile", new FileBody(imageFile)); } catch (Exception e) { throw new GalleryConnectionException(e.getMessage()); } return multiPartEntity; }