List of usage examples for org.apache.http.entity.mime MultipartEntity addPart
public void addPart(final String name, final ContentBody contentBody)
From source file:com.qsoft.components.gallery.utils.GalleryUtils.java
private static MultipartEntity addParamsForUpload(File file, String imageType, String imageName, Long equipmentId, Long userId, String locationDTO, Long equipmentHistoryId) throws UnsupportedEncodingException { MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpEntity.addPart(ConstantImage.IMAGE_FILE, new FileBody(file)); mpEntity.addPart(ConstantImage.IMAGE_TYPE, new StringBody(imageType.toUpperCase())); mpEntity.addPart(ConstantImage.IMAGE_NAME, new StringBody(imageName.toUpperCase())); if (equipmentId != null) { mpEntity.addPart(ConstantImage.EQUIPMENT_ID, new StringBody(equipmentId.toString())); }//from w w w . ja v a2s. c o m if (userId != null) { mpEntity.addPart(ConstantImage.USER_ID, new StringBody(userId.toString())); } if (equipmentHistoryId != null) { mpEntity.addPart(ConstantImage.EQUIPMENTHISTORY_ID, new StringBody(equipmentHistoryId.toString())); } mpEntity.addPart(ConstantImage.IMAGE_LOCATION_DTO, new StringBody(locationDTO)); return mpEntity; }
From source file:eu.liveandgov.ar.utilities.OS_Utils.java
/** * Remotely recognize captured image/*from www. ja va 2s . com*/ * * @param url * @param nameValuePairs */ public static HttpResponse remote_rec(String url, List<NameValuePair> nameValuePairs, Context ctx) { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); try { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int index = 0; index < nameValuePairs.size(); index++) { if (nameValuePairs.get(index).getName().equalsIgnoreCase("upload")) entity.addPart("upload", new FileBody(new File(nameValuePairs.get(index).getValue()))); else entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); } httpPost.setEntity(entity); HttpResponse httpresponse = httpClient.execute(httpPost, localContext); return httpresponse; } catch (Exception e) { //Toast.makeText(ctx, "Can not send for recognition. Internet accessible?", Toast.LENGTH_LONG).show(); Log.e("ERROR", "Can not send for recognition. Internet accessible?"); return null; } }
From source file:setiquest.renderer.Utils.java
/** * Send a random BSON file./*from w w w. j a v a 2 s .c om*/ * @return the response from the web server. */ public static String sendRandomBsonFile() { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(getOfflineSubjectsURL()); String filename = getRandomFile(getBsonDataDir()); File f = new File(filename); if (!f.exists()) { Log.log("sendRandonBsonFile(): File \"" + filename + "\" does not exists."); return "sendRandonBsonFile(): File \"" + filename + "\" does not exists."; } //Parse info from the name. //Old file = act1207.1.5.bson = actId, pol, subchannel //New file name: act1207.1.0.5.bson = actid, pol, obsType, subchannel int actId = 0; int obsId = 0; int pol = 0; String subchannel = "0"; String shortName = f.getName(); String[] parts = shortName.split("\\."); if (parts.length == 4) //Old name type { actId = Integer.parseInt(parts[0].substring(3)); obsId = 0; //Default to this. pol = Integer.parseInt(parts[1]); subchannel = parts[2]; } else if (parts.length == 5) //New name type { actId = Integer.parseInt(parts[0].substring(3)); pol = Integer.parseInt(parts[1]); obsId = Integer.parseInt(parts[2]); subchannel = parts[3]; } else { Log.log("sendRandonBsonFile(): bad bson file name: " + shortName); return "sendRandonBsonFile(): bad bson file name: " + shortName; } Log.log("Sending " + filename + ", Act:" + actId + ", Obs type:" + obsId + ", Pol" + pol + ", subchannel:" + subchannel); FileBody bin = new FileBody(new File(filename)); try { StringBody comment = new StringBody("Filename: " + filename); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", bin); reqEntity.addPart("type", new StringBody("data/bson")); reqEntity.addPart("subject[activity_id]", new StringBody("" + actId)); reqEntity.addPart("subject[observation_id]", new StringBody("" + obsId)); reqEntity.addPart("subject[pol]", new StringBody("" + pol)); reqEntity.addPart("subject[subchannel]", new StringBody("" + subchannel)); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); //Log.log(response.toString()); String sendResult = "Sending: " + shortName + "\n"; sendResult += "subject[activity_id]: " + actId + "\n"; sendResult += "subject[observation_id]: " + obsId + "\n"; sendResult += "subject[pol]: " + pol + "\n"; sendResult += "subject[subchannel]: " + subchannel + "\n"; sendResult += response.toString() + "|\n"; return sendResult; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "undefined"; }
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.mashape.client.http.HttpClient.java
public static <T> MashapeResponse<T> doRequest(Class<T> clazz, HttpMethod httpMethod, String url, Map<String, Object> parameters, ContentType contentType, ResponseType responseType, List<Authentication> authenticationHandlers) { if (authenticationHandlers == null) authenticationHandlers = new ArrayList<Authentication>(); if (parameters == null) parameters = new HashMap<String, Object>(); // Sanitize null parameters Set<String> keySet = new HashSet<String>(parameters.keySet()); for (String key : keySet) { if (parameters.get(key) == null) { parameters.remove(key);//from w ww . ja va 2 s . com } } List<Header> headers = new LinkedList<Header>(); // Handle authentications for (Authentication authentication : authenticationHandlers) { if (authentication instanceof HeaderAuthentication) { headers.addAll(authentication.getHeaders()); } else { Map<String, String> queryParameters = authentication.getQueryParameters(); if (authentication instanceof QueryAuthentication) { parameters.putAll(queryParameters); } else if (authentication instanceof OAuth10aAuthentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_SECRET) == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token','access_secret') with not null values"); } headers.add(new BasicHeader("x-mashape-oauth-consumerkey", queryParameters.get(OAuthAuthentication.CONSUMER_KEY))); headers.add(new BasicHeader("x-mashape-oauth-consumersecret", queryParameters.get(OAuthAuthentication.CONSUMER_SECRET))); headers.add(new BasicHeader("x-mashape-oauth-accesstoken", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN))); headers.add(new BasicHeader("x-mashape-oauth-accesssecret", queryParameters.get(OAuthAuthentication.ACCESS_SECRET))); } else if (authentication instanceof OAuth2Authentication) { if (url.endsWith("/oauth_url") == false && (queryParameters == null || queryParameters.get(OAuthAuthentication.ACCESS_TOKEN) == null)) { throw new RuntimeException( "Before consuming OAuth endpoint, invoke authorize('access_token') with a not null value"); } parameters.put("access_token", queryParameters.get(OAuthAuthentication.ACCESS_TOKEN)); } } } headers.add(new BasicHeader("User-Agent", USER_AGENT)); HttpUriRequest request = null; switch (httpMethod) { case GET: request = new HttpGet(url + "?" + HttpUtils.getQueryString(parameters)); break; case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; case DELETE: request = new HttpDeleteWithBody(url); break; } for (Header header : headers) { request.addHeader(header); } if (httpMethod != HttpMethod.GET) { switch (contentType) { case BINARY: MultipartEntity entity = new MultipartEntity(); for (Entry<String, Object> parameter : parameters.entrySet()) { if (parameter.getValue() instanceof File) { entity.addPart(parameter.getKey(), new FileBody((File) parameter.getValue())); } else { try { entity.addPart(parameter.getKey(), new StringBody(parameter.getValue().toString(), Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } ((HttpEntityEnclosingRequestBase) request).setEntity(entity); break; case FORM: try { ((HttpEntityEnclosingRequestBase) request) .setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } break; case JSON: throw new RuntimeException("Not supported content type: JSON"); } } org.apache.http.client.HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); MashapeResponse<T> mashapeResponse = HttpUtils.getResponse(responseType, response); return mashapeResponse; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.careerly.utils.HttpClientUtils.java
/** * post???// w w w. j a va 2s.co m * * @param url url * @param fileList * @return */ public static String postFile(String url, List<File> fileList) { HttpPost httppost = new HttpPost(url); String content = null; //1.? MultipartEntity reqEntity = new MultipartEntity(null, null, Consts.UTF_8); for (File tempFile : fileList) { reqEntity.addPart(tempFile.getName(), new FileBody(tempFile)); } httppost.setEntity(reqEntity); try { HttpResponse response = HttpClientUtils.client.execute(httppost); content = EntityUtils.toString(response.getEntity()); } catch (IOException e) { HttpClientUtils.logger.error("postFileForResponse error " + e); } return content; }
From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCallerUtils.java
/** * Constructs application/form-data entity based upon the specified parameters. * /* ww w . j av a2 s . c om*/ * @param formParams * form parameters * @return request application/form-data entity for the service */ private static HttpEntity constructFormDataEntity(List<ExecutionFormParam> formParams) { MultipartEntity entity = new MultipartEntity(); try { for (ExecutionFormParam formParam : formParams) { if (formParam.getValues() != null) { for (String value : formParam.getValues()) { entity.addPart(formParam.getName(), new StringBody(value, Consts.UTF_8)); } } else if (formParam.getFiles() != null) { for (FileValue fileValue : formParam.getFiles()) { FileBody fileBody = new FileBody(fileValue.getFile(), fileValue.getFilename(), fileValue.getMimetype(), null); entity.addPart(formParam.getName(), fileBody); } } else { entity.addPart(formParam.getName(), new StringBody("", Consts.UTF_8)); } } } catch (UnsupportedEncodingException e) { throw new WrdzRuntimeException("The encoding " + Consts.UTF_8 + " is not supported"); } return entity; }
From source file:com.openideals.android.net.HttpManager.java
public static String uploadFile(String serviceEndpoint, Properties properties, String fileParam, String file) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(serviceEndpoint); MultipartEntity entity = new MultipartEntity(); Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator(); while (i.hasNext()) { Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next(); String key = (String) entry.getKey(); String val = (String) entry.getValue(); entity.addPart(key, new StringBody(val)); }/* ww w. j a v a 2 s . c o m*/ File upload = new File(file); Log.i("httpman", "upload file (" + upload.getAbsolutePath() + ") size=" + upload.length()); entity.addPart(fileParam, new FileBody(upload)); request.setEntity(entity); HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { } else { } return response.toString(); }
From source file:info.guardianproject.net.http.HttpManager.java
public static String uploadFile(String serviceEndpoint, Properties properties, String fileParam, String file) throws Exception { HttpClient httpClient = new DefaultHttpClient(); HttpPost request = new HttpPost(serviceEndpoint); MultipartEntity entity = new MultipartEntity(); Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator(); while (i.hasNext()) { Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next(); String key = (String) entry.getKey(); String val = (String) entry.getValue(); entity.addPart(key, new StringBody(val)); }//from w w w . j a v a 2 s .com File upload = new File(file); Log.i("httpman", "upload file (" + upload.getAbsolutePath() + ") size=" + upload.length()); entity.addPart(fileParam, new FileBody(upload)); request.setEntity(entity); HttpResponse response = httpClient.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { } else { } return response.toString(); }
From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java
public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) { HttpPost post = null;//from w ww . ja va 2 s. c o m HttpResponse response = null; HTTPResponse httpResponse = new HTTPResponse(); CloseableHttpClient httpclient = null; try { httpclient = (CloseableHttpClient) createHttpClient(); post = new HttpPost(url); File file = new File(fileName); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, fileContentType); mpEntity.addPart("file", cbFile); post.setEntity(mpEntity); post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken); //post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data"); post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON); response = httpclient.execute(post); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); } catch (IOException e) { e.printStackTrace(); } StringBuffer result = new StringBuffer(); String line = ""; try { while ((line = rd.readLine()) != null) { result.append(line); } } catch (IOException e) { e.printStackTrace(); } httpResponse.setResponseCode(response.getStatusLine().getStatusCode()); httpResponse.setResponse(result.toString()); try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } return httpResponse; }