List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder build
public HttpEntity build()
From source file:com.mywork.framework.util.RemoteHttpUtil.java
/** * ?MultipartHttp??????ContentBody map/* w ww . j a v a2s . c o m*/ */ public static String fetchMultipartHttpResponse(String contentUrl, Map<String, String> headerMap, Map<String, ContentBody> bodyMap) throws IOException { try { HttpPost httpPost = new HttpPost(contentUrl); MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { httpPost.addHeader(m.getKey(), m.getValue()); } } if (bodyMap != null && !bodyMap.isEmpty()) { for (Map.Entry<String, ContentBody> m : bodyMap.entrySet()) { multipartEntityBuilder.addPart(m.getKey(), m.getValue()); } } HttpEntity reqEntity = multipartEntityBuilder.build(); httpPost.setEntity(reqEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity resEntity = response.getEntity(); String resStr = IOUtils.toString(resEntity.getContent()); return resStr; } catch (Exception e) { // TODO: handle exception } finally { response.close(); } } finally { httpClient.close(); } return null; }
From source file:me.ixfan.wechatkit.util.HttpClientUtil.java
/** * POST data using the Content-Type <code>multipart/form-data</code>. * This enables uploading of binary files etc. * * @param url URL of request./*from w w w. j a va2 s .com*/ * @param textInputs Name-Value pairs of text inputs. * @param binaryInputs Name-Value pairs of binary files inputs. * @return JSON object of response. * @throws IOException If I/O error occurs. */ public static JsonObject sendMultipartRequestAndGetJsonResponse(String url, Map<String, String> textInputs, Map<String, MultipartInput> binaryInputs) throws IOException { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); if (null != textInputs) { textInputs.forEach((k, v) -> multipartEntityBuilder.addTextBody(k, v)); } if (null != binaryInputs) { binaryInputs.forEach((k, v) -> { if (null == v.getDataBytes()) { multipartEntityBuilder.addBinaryBody(k, v.getFile(), v.getContentType(), v.getFile().getName()); } else { multipartEntityBuilder.addBinaryBody(k, v.getDataBytes(), v.getContentType(), v.getFilename()); } }); } CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.setEntity(multipartEntityBuilder.build()); return httpClient.execute(post, new JsonResponseHandler()); }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.HttpRequestFactory.java
private static HttpEntity multipartEntity(String attachmentFileName, InputStream attachmentContent) { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntityBuilder.setCharset(Charset.forName("UTF-8")); InputStreamBody inputStreamBody;/*w w w . ja v a 2 s . c o m*/ if (isNotBlank(attachmentFileName)) { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM, attachmentFileName); } else { inputStreamBody = new InputStreamBody(attachmentContent, APPLICATION_OCTET_STREAM); } multipartEntityBuilder.addPart("file", inputStreamBody); return multipartEntityBuilder.build(); }
From source file:com.game.simple.Game3.java
public static void uploadAvatar(final String token) { //---timer---// //StartReConnect(); //-----------// self.runOnUiThread(new Runnable() { public void run() { if (cropedImagePath == null) { Toast.makeText(self.getApplicationContext(), "Cha chn nh !", Toast.LENGTH_SHORT).show(); return; }//from ww w. jav a 2s . co m if (cropedImagePath.compareTo(" ") == 0) { Toast.makeText(self.getApplicationContext(), "Cha chn nh !", Toast.LENGTH_SHORT).show(); return; } else { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(url); try { File file = new File(cropedImagePath); FileBody bin = new FileBody(file); StringBody tok = new StringBody(token); StringBody imageType = new StringBody("jpg"); MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create(); multiPartEntityBuilder.addPart("token", tok); multiPartEntityBuilder.addPart("imageType", imageType); multiPartEntityBuilder.addPart("media", bin); httpPostRequest.setEntity(multiPartEntityBuilder.build()); // Execute POST request to the given URL HttpResponse httpResponse = null; httpResponse = httpClient.execute(httpPostRequest); // receive response as inputStream InputStream inputStream = null; inputStream = httpResponse.getEntity().getContent(); Log.e("--upload", "Upload complete"); Toast.makeText(self.getApplicationContext(), "Upload thnh cng!", Toast.LENGTH_SHORT) .show(); String result = ""; if (inputStream != null) result = convertInputStreamToString(inputStream); else result = " "; Log.e("upload", result); setlinkAvata(result); cropedImagePath = " "; } catch (Exception e) { Log.e("--Upload--", "ko the upload "); Toast.makeText(self.getApplicationContext(), "C li trong qu trnh upload!", Toast.LENGTH_SHORT).show(); } } //else } }); //---timer---// stopTimer(); //-----------// }
From source file:groovyx.net.http.ApacheEncoders.java
/** * Encodes multipart/form-data where the body content must be an instance of the {@link MultipartContent} class. Individual parts will be * encoded using the encoders available to the {@link ChainedHttpConfig} object. * * @param config the chained configuration object * @param ts the server adapter//from w ww.j a v a2 s. c o m */ public static void multipart(final ChainedHttpConfig config, final ToServer ts) { try { final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest(); final Object body = request.actualBody(); if (!(body instanceof MultipartContent)) { throw new IllegalArgumentException("Multipart body content must be MultipartContent."); } final String contentType = request.actualContentType(); if (!(contentType.equals(MULTIPART_FORMDATA.getAt(0)) || contentType.equals(MULTIPART_MIXED.getAt(0)))) { throw new IllegalArgumentException("Multipart body content must be multipart/form-data."); } final String boundary = randomString(10); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create().setBoundary(boundary); final String boundaryContentType = "multipart/form-data; boundary=" + boundary; entityBuilder.setContentType(ContentType.parse(boundaryContentType)); for (final MultipartContent.MultipartPart mpe : ((MultipartContent) body).parts()) { if (mpe.getFileName() == null) { entityBuilder.addTextBody(mpe.getFieldName(), (String) mpe.getContent()); } else { final byte[] encodedBytes = EmbeddedEncoder.encode(config, mpe.getContentType(), mpe.getContent()); entityBuilder.addBinaryBody(mpe.getFieldName(), encodedBytes, parse(mpe.getContentType()), mpe.getFileName()); } } request.setContentType(boundaryContentType); ts.toServer(entityBuilder.build().getContent()); } catch (IOException ioe) { ioe.printStackTrace(); } }
From source file:org.rapidoid.http.HttpClientUtil.java
private static NByteArrayEntity paramsBody(Map<String, Object> data, Map<String, List<Upload>> files) { data = U.safe(data);//from w w w . jav a2s . c om files = U.safe(files); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Map.Entry<String, List<Upload>> entry : files.entrySet()) { for (Upload file : entry.getValue()) { builder = builder.addBinaryBody(entry.getKey(), file.content(), ContentType.DEFAULT_BINARY, file.filename()); } } for (Map.Entry<String, Object> entry : data.entrySet()) { String name = entry.getKey(); String value = String.valueOf(entry.getValue()); builder = builder.addTextBody(name, value, ContentType.DEFAULT_TEXT); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { builder.build().writeTo(stream); } catch (IOException e) { throw U.rte(e); } byte[] bytes = stream.toByteArray(); return new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA); }
From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java
private static HttpEntity getAsEntity(final HttpParameter[] params) throws UnsupportedEncodingException { if (params == null) return null; if (!HttpParameter.containsFile(params)) return new HttpParameterFormEntity(params); final MultipartEntityBuilder me = MultipartEntityBuilder.create(); for (final HttpParameter param : params) { if (param.isFile()) { final ContentType contentType = ContentType.create(param.getContentType()); final ContentBody body; if (param.getFile() != null) { body = new FileBody(param.getFile(), ContentType.create(param.getContentType())); } else { body = new InputStreamBody(param.getFileBody(), contentType, param.getFileName()); }/* w w w . ja v a2s.c o m*/ me.addPart(param.getName(), body); } else { final ContentType contentType = ContentType.TEXT_PLAIN.withCharset(Consts.UTF_8); final ContentBody body = new StringBody(param.getValue(), contentType); me.addPart(param.getName(), body); } } return me.build(); }
From source file:org.safegees.safegees.util.HttpUrlConnection.java
public static String performPostFileCall(String requestURL, String userCredentials, File file) { String response = null;// w w w . j av a 2 s. com MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create(); reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //reqEntity.addPart("avatar", new FileBody(file, ContentType.MULTIPART_FORM_DATA)); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(requestURL); httppost.addHeader(KEY_HEADER_AUTHORIZED, userCredentials); httppost.addHeader("ContentType", "image/png"); httppost.addHeader("Referer", "https://safegees.appspot.com/v1/user/image/upload/"); httppost.addHeader("Origin", "https://safegees.appspot.com"); httppost.addHeader("Upgrade-Insecure-Requests", "1"); httppost.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); reqEntity.addBinaryBody("avatar", file, ContentType.create("image/png"), file.getName()); httppost.setEntity(reqEntity.build()); HttpResponse httpResponse = null; try { httpResponse = httpclient.execute(httppost); Log.e("IMAGE", httpResponse.getStatusLine().getStatusCode() + ":" + httpResponse.getStatusLine().getReasonPhrase()); //response = EntityUtils.toString(httpResponse.getEntity()); response = httpResponse.getStatusLine().getReasonPhrase(); } catch (IOException e) { e.printStackTrace(); } if (httpResponse.getStatusLine().getStatusCode() == 200) return response; return null; }
From source file:org.brunocvcunha.jiphy.requests.JiphyUploadRequest.java
/** * Creates required multipart entity with the image binary * // w ww . j a va 2 s .c o m * @return HttpEntity to send on the post * @throws ClientProtocolException * @throws IOException */ protected HttpEntity createMultipartEntity() throws ClientProtocolException, IOException { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", file); HttpEntity entity = builder.build(); return entity; }
From source file:de.yaio.commons.http.HttpUtils.java
/** * execute POST-Request for url with params * @param baseUrl the url to call * @param username username for auth * @param password password for auth * @param params params for the request * @param textFileParams text-files to upload * @param binFileParams bin-files to upload * @return HttpResponse * @throws IOException possible Exception if Request-state <200 > 299 *///from w ww. java 2s . c om public static HttpResponse callPostUrlPure(final String baseUrl, final String username, final String password, final Map<String, String> params, final Map<String, String> textFileParams, final Map<String, String> binFileParams) throws IOException { // create request HttpPost request = new HttpPost(baseUrl); // map params MultipartEntityBuilder builder = MultipartEntityBuilder.create(); if (MapUtils.isNotEmpty(params)) { for (String key : params.keySet()) { builder.addTextBody(key, params.get(key), ContentType.TEXT_PLAIN); } } // map files if (MapUtils.isNotEmpty(textFileParams)) { for (String key : textFileParams.keySet()) { File file = new File(textFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_TEXT, textFileParams.get(key)); } } // map files if (MapUtils.isNotEmpty(binFileParams)) { for (String key : binFileParams.keySet()) { File file = new File(binFileParams.get(key)); builder.addBinaryBody(key, file, ContentType.DEFAULT_BINARY, binFileParams.get(key)); } } // set request HttpEntity multipart = builder.build(); request.setEntity(multipart); // add request header request.addHeader("User-Agent", "YAIOCaller"); // call url if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending 'POST' request to URL : " + baseUrl); } HttpResponse response = executeRequest(request, username, password); // get response int retCode = response.getStatusLine().getStatusCode(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response Code : " + retCode); } return response; }