List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:org.codegist.crest.HttpClientRestService.java
private static HttpUriRequest toHttpUriRequest(HttpRequest request) throws UnsupportedEncodingException { HttpUriRequest uriRequest;/*from w w w . j a va2s .co m*/ String queryString = ""; if (request.getQueryParams() != null) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : request.getQueryParams().entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } String qs = URLEncodedUtils.format(params, request.getEncoding()); queryString = Strings.isNotBlank(qs) ? ("?" + qs) : ""; } String uri = request.getUri().toString() + queryString; switch (request.getMeth()) { default: case GET: uriRequest = new HttpGet(uri); break; case POST: uriRequest = new HttpPost(uri); break; case PUT: uriRequest = new HttpPut(uri); break; case DELETE: uriRequest = new HttpDelete(uri); break; case HEAD: uriRequest = new HttpHead(uri); break; } if (uriRequest instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequestBase = ((HttpEntityEnclosingRequestBase) uriRequest); HttpEntity entity; if (Params.isForUpload(request.getBodyParams().values())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { ContentBody body; if (param.getValue() instanceof InputStream) { body = new InputStreamBody((InputStream) param.getValue(), param.getKey()); } else if (param.getValue() instanceof File) { body = new FileBody((File) param.getValue()); } else if (param.getValue() != null) { body = new StringBody(param.getValue().toString(), request.getEncodingAsCharset()); } else { body = new StringBody(null); } multipartEntity.addPart(param.getKey(), body); } entity = multipartEntity; } else { List<NameValuePair> params = new ArrayList<NameValuePair>(request.getBodyParams().size()); for (Map.Entry<String, Object> param : request.getBodyParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue() != null ? param.getValue().toString() : null)); } entity = new UrlEncodedFormEntity(params, request.getEncoding()); } enclosingRequestBase.setEntity(entity); } if (request.getHeaders() != null && !request.getHeaders().isEmpty()) { for (Map.Entry<String, String> header : request.getHeaders().entrySet()) { uriRequest.setHeader(header.getKey(), header.getValue()); } } if (request.getConnectionTimeout() != null && request.getConnectionTimeout() >= 0) { HttpConnectionParams.setConnectionTimeout(uriRequest.getParams(), request.getConnectionTimeout().intValue()); } if (request.getSocketTimeout() != null && request.getSocketTimeout() >= 0) { HttpConnectionParams.setSoTimeout(uriRequest.getParams(), request.getSocketTimeout().intValue()); } return uriRequest; }
From source file:com.shmsoft.dmass.lotus.NSFParser.java
private boolean submitProcessing(String url, String taskId, String nsfFile) { File file = new File(nsfFile); HttpClient httpClient = new DefaultHttpClient(); try {//from ww w . ja v a 2 s . c o m HttpPost post = new HttpPost(url + "/submit-processing.html"); MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file)); entity.addPart("taskId", new StringBody(taskId)); post.setEntity(entity); HttpResponse response = httpClient.execute(post); getResponseMessage(response); } catch (Exception e) { System.out.println("NSFParser -- Problem sending data: " + e.getMessage()); return false; } return true; }
From source file:org.jacocoveralls.jacocoveralls.JacocoverallsMojo.java
public void sendToCoveralls() throws MojoExecutionException { try {//from www . j a v a2s. c om FileBody data = new FileBody(targetFile, "application/octet-stream", sourceEncoding); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(COVERALLS_API); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("json_file", data); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if ("HTTP/1.1 200 OK".equals(response.getStatusLine())) { getLog().info("Data has been sent to coveralls."); } else { getLog().error("Error sending data to coveralls."); } } catch (UnsupportedEncodingException e) { throw new MojoExecutionException("Error sending data do Coveralls.", e); } catch (ClientProtocolException e) { throw new MojoExecutionException("Error sending data do Coveralls.", e); } catch (IOException e) { throw new MojoExecutionException("Error sending data do Coveralls.", e); } }
From source file:com.ecocitizen.common.HttpHelper.java
public boolean sendUploadFile(File file) { String url = SENSORMAP_UPLOADFILE_URL; if (D)/*from w w w .j av a 2 s.co m*/ Log.d(TAG, url); HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(url); request.setHeader("User-Agent", HTTP_USER_AGENT); MultipartEntity entity = new MultipartEntity(); ContentBody contentBody = new FileBody(file); FormBodyPart bodyPart = new FormBodyPart("file", contentBody); entity.addPart(bodyPart); request.setEntity(entity); try { HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == HTTP_STATUS_OK) { mLastStatus = Status.SUCCESS; return true; } } catch (ClientProtocolException e) { mLastStatus = Status.EXCEPTION; e.printStackTrace(); Log.e(TAG, "Exception in sendUploadFile"); } catch (IOException e) { mLastStatus = Status.EXCEPTION; e.printStackTrace(); Log.e(TAG, "Exception in sendUploadFile"); } return false; }
From source file:net.rcarz.jiraclient.RestClient.java
private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException { if (file != null) { File fileUpload = file;//from w ww.jav a2 s . c om req.setHeader("X-Atlassian-Token", "nocheck"); MultipartEntity ent = new MultipartEntity(); ent.addPart("file", new FileBody(fileUpload)); req.setEntity(ent); } return request(req); }
From source file:com.amalto.workbench.utils.HttpClientUtil.java
private static HttpUriRequest createUploadRequest(String URL, String userName, String localFilename, String filename, String imageCatalog, HashMap<String, String> picturePathMap) { HttpPost request = new HttpPost(URL); MultipartEntity entity = new MultipartEntity(); if (!Messages.Util_24.equalsIgnoreCase(localFilename)) { File file = new File(localFilename); if (file.exists()) { entity.addPart("imageFile", new FileBody(file)); //$NON-NLS-1$ }/*ww w. j a v a 2 s . co m*/ } if (imageCatalog != null) { entity.addPart("catalogName", StringBody.create(imageCatalog, STRING_CONTENT_TYPE, null)); //$NON-NLS-1$ } if (filename != null) { int pos = filename.lastIndexOf('.'); if (pos != -1) { filename = filename.substring(0, pos); } entity.addPart("fileName", StringBody.create(filename, STRING_CONTENT_TYPE, null)); //$NON-NLS-1$ } request.setEntity(entity); addStudioToken(request, userName); return request; }
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 *//* w w w .jav 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.hoiio.api.FaxAPI.java
/*** * Sends a fax specified by the method parameters * @see <a href="http://developer.hoiio.com/docs/fax_send.html">http://developer.hoiio.com/docs/fax_send.html</a> * @param auth The user authorization object for the request * @param sender The sender number or caller id to be displayed * @param dest The destination to send the fax to. Phone numbers should start with a "+" and country code (E.164 format), e.g. +6511111111. * @param filepath The path of the fax to be sent * @param filename The file name of the fax desired * @return A unique reference ID for this fax transaction. This parameter will not be present if the request was not successful. * @throws HttpPostConnectionException if there is a connection failure * @throws HoiioRestException if there were problems using this REST API *///from w w w . jav a2s.c o m public static String sendFax(HoiioAuth auth, String sender, String dest, String filepath, String filename) throws HttpPostConnectionException, HoiioRestException { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost method = new HttpPost(APIUrls.SEND_FAX); MultipartEntity entity = new MultipartEntity(); entity.addPart("app_id", new StringBody(auth.getAppId(), Charset.forName("UTF-8"))); entity.addPart("access_token", new StringBody(auth.getToken(), Charset.forName("UTF-8"))); entity.addPart("dest", new StringBody(dest, Charset.forName("UTF-8"))); entity.addPart("tag", new StringBody(filename, Charset.forName("UTF-8"))); entity.addPart("filename", new StringBody(filename, Charset.forName("UTF-8"))); if (sender != null && sender.length() > 0) { entity.addPart("caller_id", new StringBody(sender, Charset.forName("UTF-8"))); } FileBody fileBody = new FileBody(new File(filepath)); entity.addPart("file", fileBody); method.setEntity(entity); log.info("executing request " + method.getRequestLine()); HttpResponse httpResponse = httpclient.execute(method); String responseBody = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8"); final APIResponse response = new APIResponse(responseBody); if (response.getStatus() == APIStatus.success_ok) { return response.getResponseMap().getString("txn_ref"); } else { log.error("Error with request: " + method.getRequestLine()); log.error(response.getResponseString()); throw new HoiioRestException(new APIRequest(APIUrls.SEND_FAX, method.getRequestLine().toString()), response); } } catch (IOException ex) { throw new HttpPostConnectionException(ex); } }
From source file:com.ctctlabs.ctctwsjavalib.CTCTConnection.java
/** * Perform a multipart post request to the web service * @param link URL to perform the post request * @param content the string part/*w ww . ja v a 2 s.co m*/ * @param baData the byte array part * @param fileName the file name in the byte array part * @return response entity content returned by the web service * @throws ClientProtocolException * @throws IOException * @author CL Kim */ InputStream doPostMultipartRequest(String link, String content, byte[] baData, String fileName) throws ClientProtocolException, IOException { HttpPost httppost = new HttpPost(link); StringBody sbody = new StringBody(content); FormBodyPart fbp1 = new FormBodyPart("imageatomxmlpart", sbody); fbp1.addField("Content-Type", "application/atom+xml"); //fbp1.addField("Accept", "application/atom+xml"); ByteArrayBody babody = new ByteArrayBody(baData, fileName); FormBodyPart fbp2 = new FormBodyPart("imagejpegpart", babody); fbp2.addField("Content-Type", "image/jpeg"); fbp2.addField("Transfer-Encoding", "binary"); //fbp2.addField("Accept", "application/atom+xml"); MultipartEntity reqEntity = new MultipartEntity(); // HttpMultipartMode.STRICT is default, cannot be HttpMultipartMode.BROWSER_COMPATIBLE reqEntity.addPart(fbp1); reqEntity.addPart(fbp2); httppost.setEntity(reqEntity); if (accessToken != null) httppost.setHeader("Authorization", "Bearer " + accessToken); // for OAuth2.0 HttpResponse response = httpclient.execute(httppost); if (response != null) { responseStatusCode = response.getStatusLine().getStatusCode(); responseStatusReason = response.getStatusLine().getReasonPhrase(); // If receive anything but a 201 status, return a null input stream if (responseStatusCode == HttpStatus.SC_CREATED) { return response.getEntity().getContent(); } return null; } else { responseStatusCode = 0; // reset to initial default responseStatusReason = null; // reset to initial default return null; } }
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 w w . ja v a 2s. c om*/ } } 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); } }