List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity
public MultipartEntity()
From source file:com.ushahidi.android.app.net.MainHttpClient.java
/** * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no * data, 8 - api disabled, 9 - no task found, 10 - json is wrong *///from w w w . j a va 2s.c o m public static int PostFileUpload(String URL, HashMap<String, String> params) throws IOException { Log.d(CLASS_TAG, "PostFileUpload(): upload file to server."); entity = new MultipartEntity(); // Dipo Fix try { // wrap try around because this constructor can throw Error final HttpPost httpost = new HttpPost(URL); if (params != null) { entity.addPart("task", new StringBody(params.get("task"))); entity.addPart("incident_title", new StringBody(params.get("incident_title"), Charset.forName("UTF-8"))); entity.addPart("incident_description", new StringBody(params.get("incident_description"), Charset.forName("UTF-8"))); entity.addPart("incident_date", new StringBody(params.get("incident_date"))); entity.addPart("incident_hour", new StringBody(params.get("incident_hour"))); entity.addPart("incident_minute", new StringBody(params.get("incident_minute"))); entity.addPart("incident_ampm", new StringBody(params.get("incident_ampm"))); entity.addPart("incident_category", new StringBody(params.get("incident_category"))); entity.addPart("latitude", new StringBody(params.get("latitude"))); entity.addPart("longitude", new StringBody(params.get("longitude"))); entity.addPart("location_name", new StringBody(params.get("location_name"), Charset.forName("UTF-8"))); entity.addPart("person_first", new StringBody(params.get("person_first"), Charset.forName("UTF-8"))); entity.addPart("person_last", new StringBody(params.get("person_last"), Charset.forName("UTF-8"))); entity.addPart("person_email", new StringBody(params.get("person_email"), Charset.forName("UTF-8"))); if (!TextUtils.isEmpty(params.get("filename"))) { File file = new File(params.get("filename")); if (file.exists()) { entity.addPart("incident_photo[]", new FileBody(new File(params.get("filename")))); } } // NEED THIS NOW TO FIX ERROR 417 httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false); httpost.setEntity(entity); HttpResponse response = httpClient.execute(httpost); Preferences.httpRunning = false; HttpEntity respEntity = response.getEntity(); if (respEntity != null) { InputStream serverInput = respEntity.getContent(); return Util.extractPayloadJSON(GetText(serverInput)); } } } catch (MalformedURLException ex) { Log.d(CLASS_TAG, "PostFileUpload(): MalformedURLException"); ex.printStackTrace(); return 11; // fall through and return false } catch (IllegalArgumentException ex) { Log.e(CLASS_TAG, ex.toString()); //invalid URI return 12; } catch (IOException e) { Log.e(CLASS_TAG, e.toString()); //timeout return 13; } return 10; }
From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java
@Test public void testFileUploadWithEagerParsingAndNonASCIIFilename() throws Exception { DefaultServer.setRootHandler(new EagerFormParsingHandler().setNext(createHandler())); TestHttpClient client = new TestHttpClient(); try {/*from w w w .j av a2 s . c om*/ HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path"); MultipartEntity entity = new MultipartEntity(); entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8)); File uploadfile = new File( MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()); FormBodyPart filePart = new FormBodyPart("file", new FileBody(uploadfile, "", "application/octet-stream", Charsets.UTF_8.toString())); filePart.addField("Content-Disposition", "form-data; name=\"file\"; filename*=\"utf-8''%CF%84%CE%B5%CF%83%CF%84.txt\""); entity.addPart(filePart); post.setEntity(entity); HttpResponse result = client.execute(post); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } }
From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {//from w ww .j a v a 2 s . c o m HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URI url_orig; try { url_orig = new URI(url_string); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = url_orig.getHost(), authority = url_orig.getAuthority(); final String resolved_host = resolver != null ? resolver.resolve(host) : null; final String resolved_url = !isEmpty(resolved_host) ? url_string.replace("://" + host, "://" + resolved_host) : url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter parameter : params) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : params) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new TwitterException("Unsupported request method " + req.getMethod()); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (!isEmpty(resolved_host) && !resolved_host.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:bluej.collect.DataCollectorImpl.java
public static void compiled(Project proj, Package pkg, File[] sources, List<DiagnosticWithShown> diagnostics, boolean success) { MultipartEntity mpe = new MultipartEntity(); mpe.addPart("event[compile_success]", CollectUtility.toBody(success)); ProjectDetails projDetails = new ProjectDetails(proj); for (File src : sources) { mpe.addPart("event[compile_input][][source_file_name]", CollectUtility.toBody(CollectUtility.toPath(projDetails, src))); }// www . j ava 2s. c o m for (DiagnosticWithShown dws : diagnostics) { final Diagnostic d = dws.getDiagnostic(); mpe.addPart("event[compile_output][][is_error]", CollectUtility.toBody(d.getType() == Diagnostic.ERROR)); mpe.addPart("event[compile_output][][shown]", CollectUtility.toBody(dws.wasShownToUser())); mpe.addPart("event[compile_output][][message]", CollectUtility.toBody(d.getMessage())); if (d.getFileName() != null) { mpe.addPart("event[compile_output][][start_line]", CollectUtility.toBody(d.getStartLine())); mpe.addPart("event[compile_output][][end_line]", CollectUtility.toBody(d.getEndLine())); mpe.addPart("event[compile_output][][start_column]", CollectUtility.toBody(d.getStartColumn())); mpe.addPart("event[compile_output][][end_column]", CollectUtility.toBody(d.getEndColumn())); // Must make file name relative for anonymisation: String relative = CollectUtility.toPath(projDetails, new File(d.getFileName())); mpe.addPart("event[compile_output][][source_file_name]", CollectUtility.toBody(relative)); } } submitEvent(proj, pkg, EventName.COMPILE, new PlainEvent(mpe)); }
From source file:li.zeitgeist.api.ZeitgeistApi.java
public List<Item> createByFiles(List<File> files, String tags, boolean announce, OnProgressListener listener) throws ZeitgeistError { MultipartEntity entity;//from w w w . j ava 2 s . c o m if (listener == null) { entity = new MultipartEntity(); } else { entity = new MultipartEntityWithProgress(listener); } for (File file : files) { entity.addPart("image_upload[]", new FileBody(file)); } try { entity.addPart("tags", new StringBody(tags)); entity.addPart("announce", new StringBody(announce ? "true" : "false")); } catch (UnsupportedEncodingException e) { throw new ZeitgeistError("UnsupportedEncoding: " + e.getMessage()); } Map<String, ?> jsonObject = postRequest("/new", entity); ArrayList<Map<String, ?>> itemObjects = (ArrayList<Map<String, ?>>) jsonObject.get("items"); List<Item> items = new Vector<Item>(); for (Map<String, ?> itemObject : itemObjects) { items.add(new Item(itemObject, baseUrl)); } return items; }
From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { try {// w w w . j a va2 s .c om HttpRequestBase commonsRequest; final HostAddressResolver resolver = conf.getHostAddressResolver(); final String urlString = req.getURL(); final URI urlOrig; try { urlOrig = new URI(urlString); } catch (final URISyntaxException e) { throw new TwitterException(e); } final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGet(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPost post = new HttpPost(resolvedUrl); // parameter has a file? boolean hasFile = false; final HttpParameter[] params = req.getParameters(); if (params != null) { for (final HttpParameter param : params) { if (param.isFile()) { hasFile = true; break; } } if (!hasFile) { if (params.length > 0) { post.setEntity(new UrlEncodedFormEntity(params)); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), param.getContentType()); } else { body = new InputStreamBody(param.getFileBody(), param.getFileName(), param.getContentType()); } me.addPart(param.getName(), body); } else { final ContentBody body = new StringBody(param.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(param.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolvedUrl); } else if (method == RequestMethod.PUT) { commonsRequest = new HttpPut(resolvedUrl); } else throw new TwitterException("Unsupported request method " + method); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader("Host", authority); } final ApacheHttpClientHttpResponseImpl res; try { res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { throw new TwitterException(e); } }
From source file:org.eclipse.cbi.maven.plugins.winsigner.SignMojo.java
/** * helper to send the file to the signing service * @param source file to send/* w ww . j a v a2s . c o m*/ * @param target file to copy response to * @throws IOException * @throws MojoExecutionException */ private void postFile(File source, File target) throws IOException, MojoExecutionException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(signerUrl); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(source)); post.setEntity(reqEntity); HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity resEntity = response.getEntity(); if (statusCode >= 200 && statusCode <= 299 && resEntity != null) { InputStream is = resEntity.getContent(); try { FileUtils.copyStreamToFile(new RawInputStreamFacade(is), target); } finally { IOUtil.close(is); } } else { throw new MojoExecutionException("Signer replied " + response.getStatusLine()); } }
From source file:com.vmware.photon.controller.client.RestClient.java
public HttpResponse upload(String path, String inputFileName, Map<String, String> arguments) throws IOException { HttpClient client = getHttpClient(); HttpPost httppost = new HttpPost(target + path); File file = new File(inputFileName); if (sharedSecret != null) { httppost.addHeader(AUTHORIZATION_HEADER, AUTHORIZATION_METHOD + sharedSecret); }/*w w w. j a v a2s . c o m*/ MultipartEntity mpEntity = new MultipartEntity(); FileBody cbFile = new FileBody(file, "application/octect-stream"); for (Map.Entry<String, String> argument : arguments.entrySet()) { StringBody stringBody = new StringBody(argument.getValue()); mpEntity.addPart(argument.getKey(), stringBody); } mpEntity.addPart("file", cbFile); httppost.setEntity(mpEntity); return client.execute(httppost); }
From source file:com.alibaba.openapi.client.rpc.AbstractHttpRequestBuilder.java
public HttpRequest getHttpRequest(InvokeContext context) { final RequestPolicy requestPolicy = context.getPolicy(); final StringBuilder path = getProtocolRequestPath(context, getProtocol()); final StringBuilder queryString = new StringBuilder(); final String method; final List<NameValuePair> parameters = buildParams(context); buildSysParams(parameters, queryString, context, requestPolicy); HttpEntity entity = null;// ww w. j ava 2s. c om switch (requestPolicy.getHttpMethod()) { case POST: method = METHOD_POST; break; case GET: method = METHOD_GET; break; case AUTO: if (hasParameters(parameters) || hasAttachments(context.getRequest())) { method = METHOD_POST; } else { method = METHOD_GET; } break; default: method = METHOD_POST; } if (hasParameters(parameters)) { if (METHOD_GET.equals(method)) { if (queryString.length() > 0) { queryString.append(PARAMETER_SEPARATOR); } queryString.append(URLEncodedUtils.format(parameters, requestPolicy.getQueryStringCharset())); } else { try { entity = new UrlEncodedFormEntity(parameters, requestPolicy.getContentCharset()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } } } signature(path, queryString, parameters, requestPolicy); HttpRequest httpRequest; try { httpRequest = requestFactory.newHttpRequest(method, getApiRequestPath(context, requestPolicy) .append('/').append(path).append(QUERY_STRING_SEPARATOR).append(queryString).toString()); } catch (MethodNotSupportedException e) { throw new UnsupportedOperationException("Unsupported http request method:" + e.getMessage(), e); } if (httpRequest instanceof BasicHttpEntityEnclosingRequest) { if (hasAttachments(context.getRequest())) { MultipartEntity multipartEntity = new MultipartEntity(); for (Entry<String, String> entry : context.getRequest().getAttachments().entrySet()) { File file = new File(entry.getValue()); multipartEntity.addPart(entry.getKey(), new FileBody(file)); } entity = multipartEntity; } else if (requestPolicy.getRequestCompressThreshold() >= 0 && entity.getContentLength() > requestPolicy.getRequestCompressThreshold()) { entity = new GzipCompressingNEntity(entity); httpRequest.addHeader("Content-Encoding", "gzip"); } ((BasicHttpEntityEnclosingRequest) httpRequest).setEntity(entity); } // httpRequest.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // httpRequest.addHeader("Accept-Charset", "gb18030,utf-8;q=0.7,*;q=0.3"); // httpRequest.addHeader("Accept-Encoding", "gzip,deflate,sdch"); // httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.8"); // httpRequest.addHeader("Cache-Control", "max-age=0"); // httpRequest.addHeader("Connection", "keep-alive"); return httpRequest; }
From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java
@Override public twitter4j.internal.http.HttpResponse request(final twitter4j.internal.http.HttpRequest req) throws TwitterException { try {// www .j ava2 s .c o m HttpRequestBase commonsRequest; //final HostAddressResolver resolver = conf.getHostAddressResolver(); final String url_string = req.getURL(); final URL url_orig = new URL(url_string); final String host = url_orig.getHost(); //final String resolved_host = resolver != null ? resolver.resolve(host) : null; //final String resolved_url = resolved_host != null ? url_string.replace("://" + host, "://" + resolved_host) // : url_string; final String resolved_url = url_string; if (req.getMethod() == RequestMethod.GET) { commonsRequest = new HttpGet(resolved_url); } else if (req.getMethod() == RequestMethod.POST) { final HttpPost post = new HttpPost(resolved_url); // parameter has a file? boolean hasFile = false; if (req.getParameters() != null) { for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { hasFile = true; break; } } if (!hasFile) { final ArrayList<NameValuePair> args = new ArrayList<NameValuePair>(); for (final HttpParameter parameter : req.getParameters()) { args.add(new BasicNameValuePair(parameter.getName(), parameter.getValue())); } if (args.size() > 0) { post.setEntity(new UrlEncodedFormEntity(args, "UTF-8")); } } else { final MultipartEntity me = new MultipartEntity(); for (final HttpParameter parameter : req.getParameters()) { if (parameter.isFile()) { final ContentBody body = new FileBody(parameter.getFile(), parameter.getContentType()); me.addPart(parameter.getName(), body); } else { final ContentBody body = new StringBody(parameter.getValue(), "text/plain; charset=UTF-8", Charset.forName("UTF-8")); me.addPart(parameter.getName(), body); } } post.setEntity(me); } } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (req.getMethod() == RequestMethod.DELETE) { commonsRequest = new HttpDelete(resolved_url); } else if (req.getMethod() == RequestMethod.HEAD) { commonsRequest = new HttpHead(resolved_url); } else if (req.getMethod() == RequestMethod.PUT) { commonsRequest = new HttpPut(resolved_url); } else throw new AssertionError(); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } String authorizationHeader; if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) { commonsRequest.addHeader("Authorization", authorizationHeader); } //if (resolved_host != null && !host.equals(resolved_host)) { //commonsRequest.addHeader("Host", host); //} final ApacheHttpClientHttpResponseImpl res = new ApacheHttpClientHttpResponseImpl( client.execute(commonsRequest), conf); final int statusCode = res.getStatusCode(); if (statusCode < OK && statusCode > ACCEPTED) throw new TwitterException(res.asString(), res); return res; } catch (final IOException e) { throw new TwitterException(e); } }